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 |
||
18 | trait AuditableTrait |
||
19 | { |
||
20 | /** |
||
21 | * Boot the audit trait for a model. |
||
22 | * |
||
23 | * @return void |
||
24 | */ |
||
25 | public static function bootAuditableTrait() |
||
29 | |||
30 | /** |
||
31 | * Get user model who created the record. |
||
32 | * |
||
33 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo |
||
34 | */ |
||
35 | public function creator() |
||
39 | |||
40 | /** |
||
41 | * Get column name for created by. |
||
42 | * |
||
43 | * @return string |
||
44 | */ |
||
45 | protected function getCreatedByColumn() |
||
49 | |||
50 | /** |
||
51 | * Get user model who updated the record. |
||
52 | * |
||
53 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo |
||
54 | */ |
||
55 | public function updater() |
||
59 | |||
60 | /** |
||
61 | * Get column name for updated by. |
||
62 | * |
||
63 | * @return string |
||
64 | */ |
||
65 | protected function getUpdatedByColumn() |
||
69 | |||
70 | /** |
||
71 | * Get created by user full name. |
||
72 | * |
||
73 | * @return string |
||
74 | */ |
||
75 | View Code Duplication | public function getCreatedByNameAttribute() |
|
85 | |||
86 | /** |
||
87 | * Get Laravel's user class instance. |
||
88 | * |
||
89 | * @return \Illuminate\Database\Eloquent\Model |
||
90 | */ |
||
91 | public function getUserInstance() |
||
97 | |||
98 | /** |
||
99 | * Get updated by user full name. |
||
100 | * |
||
101 | * @return string |
||
102 | */ |
||
103 | View Code Duplication | public function getUpdatedByNameAttribute() |
|
113 | |||
114 | /** |
||
115 | * Query scope to limit results to own records. |
||
116 | * |
||
117 | * @param \Illuminate\Database\Eloquent\Builder $query |
||
118 | * @return \Illuminate\Database\Eloquent\Builder |
||
119 | */ |
||
120 | public function scopeOwned(Builder $query) |
||
124 | |||
125 | /** |
||
126 | * Get qualified column name for user id. |
||
127 | * |
||
128 | * @return string |
||
129 | */ |
||
130 | public function getQualifiedUserIdColumn() |
||
134 | } |
||
135 |
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.