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 |
||
15 | class Cast implements CastInterface |
||
16 | { |
||
17 | /** |
||
18 | * @var array |
||
19 | */ |
||
20 | private $config; |
||
21 | |||
22 | /** |
||
23 | * @param array $config |
||
24 | */ |
||
25 | 19 | private function __construct(array $config) |
|
29 | |||
30 | /** |
||
31 | * @param array $config |
||
32 | * @return static |
||
33 | */ |
||
34 | 19 | public static function create(array $config) |
|
38 | |||
39 | /** |
||
40 | * @param array $data |
||
41 | * @return array |
||
42 | */ |
||
43 | 18 | public function execute(array $data): array |
|
47 | |||
48 | /** |
||
49 | * @param mixed $data |
||
50 | * @param array $config |
||
51 | * @return array |
||
52 | */ |
||
53 | 18 | private function cast($data, array $config) |
|
73 | |||
74 | /** |
||
75 | * @param string|int $value |
||
76 | * @return Carbon |
||
77 | */ |
||
78 | 2 | private function dateTime($value): Carbon |
|
87 | |||
88 | /** |
||
89 | * @param array $value |
||
90 | * @return array |
||
91 | */ |
||
92 | View Code Duplication | private function intArray(array $value): array |
|
100 | |||
101 | /** |
||
102 | * @param array $value |
||
103 | * @return array |
||
104 | */ |
||
105 | View Code Duplication | private function floatArray(array $value): array |
|
113 | |||
114 | /** |
||
115 | * @param array $value |
||
116 | * @return array |
||
117 | */ |
||
118 | View Code Duplication | private function strArray(array $value): array |
|
126 | |||
127 | /** |
||
128 | * @param mixed $value |
||
129 | * @return int |
||
130 | */ |
||
131 | 8 | private function integer($value): int |
|
135 | |||
136 | /** |
||
137 | * @param mixed $value |
||
138 | * @return float |
||
139 | */ |
||
140 | 2 | private function float($value): float |
|
144 | |||
145 | /** |
||
146 | * @param mixed $value |
||
147 | * @return string |
||
148 | */ |
||
149 | 8 | private function string($value): string |
|
153 | |||
154 | /** |
||
155 | * @param mixed $value |
||
156 | * @return array |
||
157 | */ |
||
158 | 1 | private function array($value): array |
|
162 | |||
163 | /** |
||
164 | * @param mixed $value |
||
165 | * @return bool |
||
166 | */ |
||
167 | 2 | private function boolean($value): bool |
|
171 | } |
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.