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 |
||
14 | class Cast implements CastInterface |
||
15 | { |
||
16 | /** |
||
17 | * @var array |
||
18 | */ |
||
19 | private $config; |
||
20 | |||
21 | /** |
||
22 | * @param array $config |
||
23 | */ |
||
24 | 7 | private function __construct(array $config) |
|
38 | |||
39 | /** |
||
40 | * @param array $config |
||
41 | * @return static |
||
42 | */ |
||
43 | 7 | public static function create(array $config) |
|
47 | |||
48 | /** |
||
49 | * @param array $data |
||
50 | * @return array |
||
51 | */ |
||
52 | 6 | public function execute(array $data): array |
|
82 | |||
83 | /** |
||
84 | * @param string $value |
||
85 | * @return Carbon |
||
86 | */ |
||
87 | private function dateTime(string $value) |
||
91 | |||
92 | /** |
||
93 | * @param array $value |
||
94 | * @return array |
||
95 | */ |
||
96 | private function intArray(array $value) |
||
104 | |||
105 | /** |
||
106 | * @param string $value |
||
107 | * @return string |
||
108 | */ |
||
109 | private function email(string $value) |
||
113 | |||
114 | /** |
||
115 | * @param string|int $value |
||
116 | * @return int |
||
117 | */ |
||
118 | 5 | private function integer($value) |
|
122 | |||
123 | /** |
||
124 | * @param string|float $value |
||
125 | * @return int |
||
126 | */ |
||
127 | private function float($value) |
||
131 | |||
132 | /** |
||
133 | * @param string|int $value |
||
134 | * @return int |
||
135 | */ |
||
136 | 5 | private function string($value) |
|
140 | |||
141 | /** |
||
142 | * @param string|array $value |
||
143 | * @return array |
||
144 | */ |
||
145 | private function array($value) |
||
149 | |||
150 | /** |
||
151 | * @param string|bool $value |
||
152 | * @return bool |
||
153 | */ |
||
154 | private function boolean($value) |
||
158 | } |
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.