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 |
||
11 | trait Representer |
||
12 | { |
||
13 | use ArraySerializer; |
||
14 | |||
15 | /** |
||
16 | * Object that is being represented |
||
17 | * or a collection handler |
||
18 | */ |
||
19 | protected $source; |
||
20 | /** |
||
21 | * Class name to be restored |
||
22 | * |
||
23 | * @var string |
||
24 | */ |
||
25 | protected $targetClassName; |
||
26 | /** |
||
27 | * Strategy indicator |
||
28 | * 1 = one |
||
29 | * 2 = collection |
||
30 | * 3 = restore one |
||
31 | * 4 = restore collection |
||
32 | * |
||
33 | * @var string |
||
34 | */ |
||
35 | protected $strategy; |
||
36 | |||
37 | 8 | public function __construct($source = null, $strategy) |
|
46 | |||
47 | public function rules() |
||
51 | |||
52 | 4 | public function setTargetClassName($name) |
|
56 | |||
57 | /** |
||
58 | * @param $name |
||
59 | * @return PropertyRule |
||
60 | */ |
||
61 | 8 | public function property($name) |
|
65 | |||
66 | /** |
||
67 | * Represent one instance |
||
68 | * |
||
69 | * @param $source |
||
70 | * @return static |
||
71 | */ |
||
72 | 6 | public static function one($source) |
|
76 | |||
77 | /** |
||
78 | * Represent collection of instances |
||
79 | * |
||
80 | * @param array $array |
||
81 | * @return static |
||
82 | */ |
||
83 | 2 | public static function collection(array $array) |
|
87 | |||
88 | 2 | protected function getCollectionRepresentation() |
|
96 | |||
97 | 6 | View Code Duplication | protected function getOneRepresentation() |
117 | |||
118 | 6 | protected function getRepresentation() |
|
130 | |||
131 | |||
132 | /** |
||
133 | * @param $className |
||
134 | * @return static |
||
135 | */ |
||
136 | 4 | public static function restore($className) |
|
142 | |||
143 | /** |
||
144 | * @param string $className |
||
145 | * @return static |
||
146 | */ |
||
147 | 1 | public static function restoreCollection($className) |
|
153 | |||
154 | 4 | protected function getReverseRepresentation($projection) |
|
166 | |||
167 | 4 | View Code Duplication | protected function getOneReverseRepresentation($projection) |
186 | |||
187 | 1 | protected function getCollectionReverseRepresentation($projectionArray) |
|
195 | } |
||
196 |
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.