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 |
||
9 | class Getter implements GetterInterface |
||
10 | { |
||
11 | /** @var bool */ |
||
12 | protected $throwOnFail; |
||
13 | |||
14 | /** @var bool */ |
||
15 | protected $ignoreProtected; |
||
16 | |||
17 | /** |
||
18 | * Getter constructor. |
||
19 | * @param bool $throwOnFail |
||
20 | * @param bool $ignoreProtected |
||
21 | */ |
||
22 | public function __construct(bool $throwOnFail = true, bool $ignoreProtected = false) |
||
27 | |||
28 | /** |
||
29 | * @param $object |
||
30 | * @param string $field |
||
31 | * @return mixed |
||
32 | */ |
||
33 | View Code Duplication | public function get($object, string $field) |
|
49 | |||
50 | /** |
||
51 | * @param $object |
||
52 | * @param string $field |
||
53 | * @return null |
||
54 | * @throws ReflectionException |
||
55 | */ |
||
56 | protected function getFromArray($object, string $field) |
||
66 | |||
67 | /** |
||
68 | * @param $object |
||
69 | * @param string $field |
||
70 | * @return mixed|null |
||
71 | * @throws ReflectionException |
||
72 | */ |
||
73 | View Code Duplication | protected function getFromObject($object, string $field) |
|
97 | |||
98 | /** |
||
99 | * @param ReflectionClass $reflectionClass |
||
100 | * @param string $field |
||
101 | * @return null|ReflectionMethod |
||
102 | */ |
||
103 | View Code Duplication | protected function findGetterMethod(ReflectionClass $reflectionClass, string $field) |
|
117 | |||
118 | /** |
||
119 | * @param ReflectionClass $reflectionClass |
||
120 | * @param string $field |
||
121 | * @return null|\ReflectionProperty |
||
122 | */ |
||
123 | View Code Duplication | protected function findProperty(ReflectionClass $reflectionClass, string $field) |
|
138 | } |
||
139 |
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.