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 |
||
18 | class AddressValidator |
||
19 | { |
||
20 | /** @var Address */ |
||
21 | private $address; |
||
22 | |||
23 | /** |
||
24 | * @param Address $address |
||
25 | */ |
||
26 | public function __construct(Address $address) |
||
30 | |||
31 | /** |
||
32 | * Validate the attributes of the address class |
||
33 | * |
||
34 | * @return void |
||
35 | */ |
||
36 | public function validate(): void |
||
43 | |||
44 | /** |
||
45 | * This validates the address line |
||
46 | * |
||
47 | * @return void |
||
48 | * @throws InvalidArgumentException |
||
49 | */ |
||
50 | View Code Duplication | private function validateAddressLine() |
|
57 | |||
58 | /** |
||
59 | * This validates the city address |
||
60 | * |
||
61 | * @return void |
||
62 | * @throws InvalidArgumentException |
||
63 | */ |
||
64 | View Code Duplication | private function validateCity() |
|
71 | |||
72 | /** |
||
73 | * This validates the state address |
||
74 | * |
||
75 | * @return void |
||
76 | * @throws InvalidArgumentException |
||
77 | */ |
||
78 | View Code Duplication | private function validateState() |
|
85 | |||
86 | /** |
||
87 | * This validates a zip code |
||
88 | * |
||
89 | * @return void |
||
90 | * @throws InvalidArgumentException |
||
91 | */ |
||
92 | View Code Duplication | private function validateZipCode() |
|
99 | } |
||
100 |
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.