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 |
||
16 | class ReflectionObject |
||
17 | { |
||
18 | private $object; |
||
19 | private $properties; |
||
20 | private $injectionStrategies; |
||
21 | |||
22 | 10 | public function __construct( |
|
36 | |||
37 | /** |
||
38 | * Add a property that will be injected |
||
39 | * |
||
40 | * @param string $name |
||
41 | * @param mixed $value |
||
42 | * |
||
43 | * @return self |
||
44 | */ |
||
45 | 4 | public function withProperty(string $name, $value) |
|
53 | |||
54 | /** |
||
55 | * Add a set of properties that need to be injected |
||
56 | * |
||
57 | * @param array $properties |
||
58 | * |
||
59 | * @return self |
||
60 | */ |
||
61 | 1 | public function withProperties(array $properties): self |
|
69 | |||
70 | /** |
||
71 | * Return the collection of properties that will be injected in the object |
||
72 | * |
||
73 | * @return CollectionInterface |
||
74 | */ |
||
75 | 2 | public function getProperties(): CollectionInterface |
|
79 | |||
80 | /** |
||
81 | * Return the list of injection strategies used |
||
82 | * |
||
83 | * @return TypedCollectionInterface |
||
84 | */ |
||
85 | 1 | public function getInjectionStrategies(): TypedCollectionInterface |
|
89 | |||
90 | /** |
||
91 | * Return the object with the list of properties set on it |
||
92 | * |
||
93 | * @return object |
||
94 | */ |
||
95 | 7 | public function buildObject() |
|
103 | |||
104 | /** |
||
105 | * Inject the given key/value pair into the object |
||
106 | * |
||
107 | * @param string $key |
||
108 | * @param mixed $value |
||
109 | * |
||
110 | * @return void |
||
111 | */ |
||
112 | 5 | private function inject(string $key, $value) |
|
127 | |||
128 | /** |
||
129 | * @param TypedCollectionInterface $strategies |
||
130 | * |
||
131 | * @return void |
||
132 | */ |
||
133 | 9 | View Code Duplication | private function initInjectionStrategies(TypedCollectionInterface $strategies = null) |
150 | } |
||
151 |
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.