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 |
||
24 | class WeatherAlert implements IteratorAggregate, WeatherAlertInterface |
||
25 | { |
||
26 | /** |
||
27 | * Alerts |
||
28 | * |
||
29 | * @var array Alerts |
||
30 | */ |
||
31 | private $alerts; |
||
32 | |||
33 | /** |
||
34 | * Weather alerts |
||
35 | * |
||
36 | * @var WeatherAlert|null Weather alert |
||
37 | */ |
||
38 | private $weatherAlert = null; |
||
39 | |||
40 | /** |
||
41 | * WeatherAlert |
||
42 | * |
||
43 | * @param WeatherAlert|null $alert set of alerts |
||
44 | */ |
||
45 | public function __construct(WeatherAlert $alert = null) |
||
49 | |||
50 | /** |
||
51 | * Get WeatherAlert containing new alert |
||
52 | * |
||
53 | * @param string $name alert name |
||
54 | * @param Alert $alert |
||
55 | * @return WeatherAlert new instance of WeatherAlert containing specified alert |
||
56 | * @throws LogicException Alert exists |
||
57 | */ |
||
58 | public function withAlert(string $name, Alert $alert): WeatherAlert |
||
68 | |||
69 | /** |
||
70 | * Get alert by name |
||
71 | * |
||
72 | * @param string $name alert name |
||
73 | * @return Alert alert |
||
74 | * @throws OutOfBoundException there is no such an alert |
||
75 | */ |
||
76 | public function getAlert(string $name): Alert |
||
88 | |||
89 | /** |
||
90 | * Iterates over alerts |
||
91 | * |
||
92 | * @return ArrayIterator alert iterator |
||
93 | */ |
||
94 | public function getIterator(): ArrayIterator |
||
98 | |||
99 | /** |
||
100 | * Get all alerts |
||
101 | * |
||
102 | * @return array all alerts |
||
103 | */ |
||
104 | public function toArray(): array |
||
116 | |||
117 | /** |
||
118 | * Check if specified alert exists |
||
119 | * |
||
120 | * @param string $name string alert name |
||
121 | * @return bool if specified alert exists return true; otherwise false |
||
122 | */ |
||
123 | public function hasAlert(string $name): bool |
||
135 | } |
||
136 |
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.