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 |
|
87 | |||
88 | /** |
||
89 | * @param Range[] $ranges |
||
90 | * @return array |
||
91 | */ |
||
92 | 3 | private function mergeRanges(array $ranges): array |
|
115 | } |
||
116 |
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVar
assignment in line 1 and the$higher
assignment in line 2 are dead. The first because$myVar
is never used and the second because$higher
is always overwritten for every possible time line.