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 |
||
11 | class DateTime implements ValidateRuleInterface |
||
12 | { |
||
13 | use DateTypeTrait, TimeTypeTrait; |
||
14 | |||
15 | /** |
||
16 | * * Indicates if the given field's value is a MySql safe DateTime. |
||
17 | * |
||
18 | * @param object $subject |
||
19 | * @param string $field |
||
20 | * |
||
21 | * @return bool |
||
22 | */ |
||
23 | 36 | public function __invoke($subject, string $field): bool |
|
41 | |||
42 | /** |
||
43 | * Validates that the string can represent a date. |
||
44 | * |
||
45 | * Valid formats include: YY-MM-DD and YYYY-MM-DD. |
||
46 | * |
||
47 | * @param string $dateString |
||
48 | * |
||
49 | * @return bool |
||
50 | */ |
||
51 | 27 | protected function validateDate(string $dateString): bool |
|
57 | |||
58 | /** |
||
59 | * Validates that the string can represent a time. |
||
60 | * |
||
61 | * @param string $timeString |
||
62 | * |
||
63 | * @return bool |
||
64 | */ |
||
65 | 21 | protected function validateTime(string $timeString): bool |
|
74 | |||
75 | /** |
||
76 | * Validates that the string can represent seconds. |
||
77 | * |
||
78 | * @param string $seconds |
||
79 | * |
||
80 | * @return bool |
||
81 | */ |
||
82 | 12 | View Code Duplication | protected function validateSeconds(string $seconds): bool |
94 | |||
95 | /** |
||
96 | * Validates that the string can represent minutes. |
||
97 | * |
||
98 | * @param string $minutes |
||
99 | * |
||
100 | * @return bool |
||
101 | */ |
||
102 | 18 | protected function validateMinutes(string $minutes): bool |
|
108 | |||
109 | /** |
||
110 | * Validates tha the string can represent hours. |
||
111 | * |
||
112 | * @param string $hours |
||
113 | * |
||
114 | * @return bool |
||
115 | */ |
||
116 | 21 | protected function validateHours(string $hours): bool |
|
122 | } |
||
123 |
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.