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 PackedBoxList implements IteratorAggregate |
||
19 | { |
||
20 | /** |
||
21 | * Average (mean) weight of boxes |
||
22 | * @var float |
||
23 | */ |
||
24 | protected $meanWeight; |
||
25 | |||
26 | /** |
||
27 | * List containing boxes |
||
28 | * @var Box[] |
||
29 | */ |
||
30 | private $list = []; |
||
31 | |||
32 | /** |
||
33 | * Has this list already been sorted? |
||
34 | * @var bool |
||
35 | */ |
||
36 | private $isSorted = false; |
||
37 | |||
38 | /** |
||
39 | * @return Traversable |
||
40 | */ |
||
41 | 11 | View Code Duplication | public function getIterator(): Traversable |
49 | |||
50 | /** |
||
51 | * Number of items in list |
||
52 | * @return int |
||
53 | */ |
||
54 | 24 | public function count(): int |
|
58 | |||
59 | /** |
||
60 | * @param PackedBox $item |
||
61 | */ |
||
62 | 27 | public function insert(PackedBox $item) |
|
66 | |||
67 | /** |
||
68 | * Do a bulk insert |
||
69 | * @internal |
||
70 | * @param PackedBox[] $boxes |
||
71 | */ |
||
72 | 6 | public function insertFromArray(array $boxes): void |
|
78 | |||
79 | /** |
||
80 | * @internal |
||
81 | * @return PackedBox |
||
82 | */ |
||
83 | 5 | View Code Duplication | public function top(): PackedBox |
91 | |||
92 | /** |
||
93 | * @param PackedBox $boxA |
||
94 | * @param PackedBox $boxB |
||
95 | * |
||
96 | * @return int |
||
97 | */ |
||
98 | 7 | View Code Duplication | private function compare(PackedBox $boxA, PackedBox $boxB): int |
109 | |||
110 | /** |
||
111 | * Calculate the average (mean) weight of the boxes |
||
112 | * @return float |
||
113 | */ |
||
114 | 7 | public function getMeanWeight(): float |
|
127 | |||
128 | /** |
||
129 | * Calculate the variance in weight between these boxes |
||
130 | * @return float |
||
131 | */ |
||
132 | 7 | public function getWeightVariance(): float |
|
144 | |||
145 | /** |
||
146 | * Get volume utilisation of the set of packed boxes |
||
147 | * @return float |
||
148 | */ |
||
149 | 1 | public function getVolumeUtilisation(): float |
|
166 | |||
167 | } |
||
168 |
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.