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 |
||
6 | class FlexDate |
||
7 | { |
||
8 | |||
9 | /** |
||
10 | * @var int|null |
||
11 | */ |
||
12 | protected $year; |
||
13 | |||
14 | /** |
||
15 | * @var int|null |
||
16 | */ |
||
17 | protected $month; |
||
18 | |||
19 | /** |
||
20 | * @var int|null |
||
21 | */ |
||
22 | protected $day; |
||
23 | |||
24 | /** |
||
25 | * @param int|null $year |
||
26 | * @param int|null $month |
||
27 | * @param int|null $day |
||
28 | */ |
||
29 | public function __construct($year = null, $month = null, $day = null) |
||
36 | |||
37 | 7 | /** |
|
38 | 7 | * @return int|null |
|
39 | 7 | */ |
|
40 | 7 | public function getYear() |
|
44 | |||
45 | 1 | /** |
|
46 | * @param int|null $year |
||
47 | 1 | */ |
|
48 | public function setYear($year) |
||
52 | |||
53 | 5 | /** |
|
54 | * @return int|null |
||
55 | 5 | */ |
|
56 | 5 | public function getMonth() |
|
60 | |||
61 | 1 | /** |
|
62 | * @param int|null $month |
||
63 | 1 | */ |
|
64 | public function setMonth($month) |
||
68 | |||
69 | 5 | /** |
|
70 | * @return int|null |
||
71 | 5 | */ |
|
72 | 5 | public function getDay() |
|
76 | |||
77 | 1 | /** |
|
78 | * @param int|null $day |
||
79 | 1 | */ |
|
80 | public function setDay($day) |
||
84 | |||
85 | 5 | /** |
|
86 | * @return bool |
||
87 | 5 | */ |
|
88 | 5 | public function hasValue() |
|
92 | |||
93 | 1 | /** |
|
94 | * @return bool |
||
95 | 1 | */ |
|
96 | public function isCompleteDate() |
||
100 | |||
101 | 2 | /** |
|
102 | * @return bool |
||
103 | 2 | */ |
|
104 | public function isValid() |
||
114 | 1 | ||
115 | 1 | /** |
|
116 | 1 | * @return bool |
|
117 | * @throws \Exception |
||
118 | */ |
||
119 | public function assertValid() |
||
131 | 1 | ||
132 | /** |
||
133 | * @return bool |
||
134 | 1 | */ |
|
135 | public function isValidDate() |
||
139 | |||
140 | 2 | /** |
|
141 | * @¶eturn \DateTime |
||
142 | 2 | */ |
|
143 | public function toDateTime() |
||
153 | 1 | ||
154 | 1 | /** |
|
155 | * {@inheritdoc} |
||
156 | 1 | */ |
|
157 | public function __toString() |
||
174 | 1 | ||
175 | 1 | /** |
|
176 | * @param string $dateString |
||
177 | 1 | * |
|
178 | * @return FlexDate |
||
179 | */ |
||
180 | public static function fromString($dateString) |
||
201 | } |
||
202 |
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.