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 | final class StdRangesCalculator implements RangesCalculator |
||
8 | { |
||
9 | /** |
||
10 | * @inheritdoc |
||
11 | */ |
||
12 | 4 | public function sum(Range ...$ranges): array |
|
13 | { |
||
14 | 4 | if (\count($ranges) === 0) { |
|
15 | 1 | return []; |
|
16 | } |
||
17 | |||
18 | 3 | $this->sortRanges($ranges); |
|
19 | 3 | return $this->mergeRanges($ranges); |
|
20 | } |
||
21 | |||
22 | /** |
||
23 | * @param Range[] $ranges |
||
24 | */ |
||
25 | private function sortRanges(array &$ranges): void |
||
31 | |||
32 | /** |
||
33 | * @inheritdoc |
||
34 | * @throws \Exception |
||
35 | */ |
||
36 | 6 | public function sub(Range $minuend, Range ...$subtrahends): array |
|
44 | |||
45 | /** |
||
46 | * @param Range $range |
||
47 | * @param Range[] $ranges |
||
48 | * @return Range[] |
||
49 | * @throws \Exception |
||
50 | */ |
||
51 | 6 | private function removeRangeFromRanges(Range $range, array $ranges): array |
|
85 | |||
86 | /** |
||
87 | * @param Range[] $ranges |
||
88 | * @return array |
||
89 | */ |
||
90 | 3 | private function mergeRanges(array $ranges): array |
|
113 | } |
||
114 |
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.