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 |
||
22 | trait ObjectById |
||
23 | { |
||
24 | |||
25 | use Object; |
||
26 | |||
27 | /** |
||
28 | * @var BaseObject[] |
||
29 | */ |
||
30 | protected $_cacheById = []; |
||
31 | |||
32 | /******************************************* |
||
33 | * FIND/GET BY ID |
||
34 | *******************************************/ |
||
35 | |||
36 | /** |
||
37 | * @param int $id |
||
38 | * @param string|null $toScenario |
||
39 | * @return BaseObject|null |
||
40 | */ |
||
41 | View Code Duplication | public function findById(int $id, string $toScenario = null) |
|
69 | |||
70 | /** |
||
71 | * @param int $id |
||
72 | * @param string|null $toScenario |
||
73 | * @return BaseObject |
||
74 | * @throws ObjectNotFoundException |
||
75 | */ |
||
76 | View Code Duplication | public function getById(int $id, string $toScenario = null): BaseObject |
|
89 | |||
90 | /** |
||
91 | * @param int $id |
||
92 | * @param string|null $toScenario |
||
93 | * @return BaseObject|null |
||
94 | */ |
||
95 | public function freshFindById(int $id, string $toScenario = null) |
||
112 | |||
113 | /** |
||
114 | * @param int $id |
||
115 | * @param string|null $toScenario |
||
116 | * @return BaseObject |
||
117 | * @throws ObjectNotFoundException |
||
118 | */ |
||
119 | View Code Duplication | public function freshGetById(int $id, string $toScenario = null): BaseObject |
|
131 | |||
132 | /** |
||
133 | * Find an existing cache by ID |
||
134 | * |
||
135 | * @param $id |
||
136 | * @return BaseObject|null |
||
137 | */ |
||
138 | public function findCacheById(int $id) |
||
151 | |||
152 | /** |
||
153 | * Identify whether in cache by ID |
||
154 | * |
||
155 | * @param $id |
||
156 | * @return bool |
||
157 | */ |
||
158 | protected function isCachedById(int $id) |
||
162 | |||
163 | /** |
||
164 | * @param ObjectWithId $object |
||
165 | * @return $this |
||
166 | */ |
||
167 | protected function cacheById(ObjectWithId $object) |
||
181 | |||
182 | /******************************************* |
||
183 | * EXCEPTIONS |
||
184 | *******************************************/ |
||
185 | |||
186 | /** |
||
187 | * @param int|null $id |
||
188 | * @throws ObjectNotFoundException |
||
189 | */ |
||
190 | protected function notFoundByIdException(int $id = null) |
||
201 | |||
202 | } |
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.