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 |
||
19 | abstract class Model |
||
20 | { |
||
21 | protected $mappingClasses = []; |
||
22 | |||
23 | /** |
||
24 | * Contains property name mappings. |
||
25 | * |
||
26 | * [ |
||
27 | * 'data_array_property1' => 'objectProperty1', |
||
28 | * 'data_array_property2' => 'objectProperty2', |
||
29 | * ] |
||
30 | * |
||
31 | * Data array property uses as keys |
||
32 | * because there is can be more then one rule per object property |
||
33 | * |
||
34 | * f.g. $data['nmodels'] and ['modelsnum'] should map in modelsCount property. |
||
35 | * Otherwise not unique array keys cause remapping of properties. |
||
36 | * |
||
37 | * @var array |
||
38 | */ |
||
39 | protected $propNameMap = []; |
||
40 | |||
41 | /** |
||
42 | * Constructor |
||
43 | * |
||
44 | * @param array $data |
||
45 | */ |
||
46 | 152 | public function __construct($data = []) |
|
50 | |||
51 | /** |
||
52 | * Set from XML |
||
53 | * |
||
54 | * @param \SimpleXMLIterator $data |
||
55 | * @return $this |
||
56 | */ |
||
57 | public function fromXml(\SimpleXMLIterator $data) |
||
104 | |||
105 | /** |
||
106 | * Set from array |
||
107 | * |
||
108 | * @param array $data |
||
109 | * @return $this |
||
110 | */ |
||
111 | 150 | public function fromArray($data) |
|
144 | |||
145 | /** |
||
146 | * Set from json |
||
147 | * |
||
148 | * @param string $json |
||
149 | * @return $this |
||
150 | */ |
||
151 | 1 | public function fromJson($json) |
|
157 | |||
158 | /** |
||
159 | * Get array from object |
||
160 | * |
||
161 | * @return array |
||
162 | */ |
||
163 | 42 | public function toArray() |
|
167 | |||
168 | /** |
||
169 | * Get array from object |
||
170 | * |
||
171 | * @return string |
||
172 | */ |
||
173 | 1 | public function toJson() |
|
177 | |||
178 | /** |
||
179 | * Get array from object |
||
180 | * |
||
181 | * @param array|object $data |
||
182 | * @return array |
||
183 | */ |
||
184 | 40 | protected function toArrayRecursive($data) |
|
222 | } |
||
223 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: