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 |
||
7 | class SubscriptionPeriod |
||
8 | { |
||
9 | |||
10 | /** @var string */ |
||
11 | const UNIT_DAILY = 'd'; |
||
12 | |||
13 | /** @var string */ |
||
14 | const UNIT_WEEKLY = 'ww'; |
||
15 | |||
16 | /** @var string */ |
||
17 | const UNIT_MONTHLY = 'm'; |
||
18 | |||
19 | /** |
||
20 | * @var string |
||
21 | * ‘d’ = daily, ‘ww’ = weekly, ‘m’ = monthly |
||
22 | */ |
||
23 | protected $unit; |
||
24 | |||
25 | /** |
||
26 | * @var int |
||
27 | * Interval between each occurrence of the subscription payments |
||
28 | */ |
||
29 | protected $interval; |
||
30 | |||
31 | /** |
||
32 | * @var int |
||
33 | * Depending on sub_period_unit |
||
34 | * Daily (d): |
||
35 | * interval in days |
||
36 | * Weekly (ww): |
||
37 | * 1=Sunday, … 7=Saturday |
||
38 | * Monthly (m): |
||
39 | * day of the month |
||
40 | */ |
||
41 | protected $moment; |
||
42 | |||
43 | /** |
||
44 | * @param string $unit |
||
45 | * @param int $interval |
||
46 | * @param int $moment |
||
47 | * @throws InvalidArgumentException |
||
48 | */ |
||
49 | 23 | public function __construct($unit, $interval, $moment) |
|
55 | |||
56 | /** |
||
57 | * @return string |
||
58 | */ |
||
59 | 4 | public function getUnit() |
|
63 | |||
64 | /** |
||
65 | * @param string $unit |
||
66 | * @throws InvalidArgumentException |
||
67 | */ |
||
68 | 23 | public function setUnit($unit) |
|
83 | |||
84 | /** |
||
85 | * @return int |
||
86 | */ |
||
87 | 5 | public function getInterval() |
|
91 | |||
92 | /** |
||
93 | * @param int $interval |
||
94 | * @throws InvalidArgumentException |
||
95 | */ |
||
96 | 22 | public function setInterval($interval) |
|
109 | |||
110 | /** |
||
111 | * @return int |
||
112 | */ |
||
113 | 5 | public function getMoment() |
|
117 | |||
118 | /** |
||
119 | * @param int $moment |
||
120 | * @throws InvalidArgumentException |
||
121 | */ |
||
122 | 19 | public function setMoment($moment) |
|
146 | } |
||
147 |
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.