Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
8 | class AuditableTraitObserver |
||
9 | { |
||
10 | /** |
||
11 | * Model's creating event hook. |
||
12 | * |
||
13 | * @param Model $model |
||
14 | */ |
||
15 | public function creating(Model $model) |
||
28 | |||
29 | /** |
||
30 | * Get authenticated user id depending on model's auth guard. |
||
31 | * |
||
32 | * @return int |
||
33 | */ |
||
34 | protected function getAuthenticatedUserId() |
||
38 | |||
39 | /** |
||
40 | * Model's updating event hook. |
||
41 | * |
||
42 | * @param Model $model |
||
43 | */ |
||
44 | View Code Duplication | public function updating(Model $model) |
|
52 | |||
53 | /** |
||
54 | * Set updatedBy column on save if value is not the same. |
||
55 | * |
||
56 | * @param \Illuminate\Database\Eloquent\Model $model |
||
57 | */ |
||
58 | View Code Duplication | public function saved(Model $model) |
|
67 | } |
||
68 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.