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 |
||
10 | class Modulo11 implements Calculator |
||
11 | { |
||
12 | use AssertionsTrait; |
||
13 | |||
14 | /** |
||
15 | * @var array Map modulo 11 remainder to check digit |
||
16 | */ |
||
17 | private static $remainderToCheck = [ |
||
18 | 0 => '0', |
||
19 | 1 => '1', |
||
20 | 2 => '2', |
||
21 | 3 => '3', |
||
22 | 4 => '4', |
||
23 | 5 => '5', |
||
24 | 6 => '6', |
||
25 | 7 => '7', |
||
26 | 8 => '8', |
||
27 | 9 => '9', |
||
28 | 10 => 'X', |
||
29 | 11 => '0', |
||
30 | ]; |
||
31 | |||
32 | /** |
||
33 | * Check if the last digit of number is a valid modulo 11 check digit |
||
34 | */ |
||
35 | 6 | public function isValid(string $number): bool |
|
53 | |||
54 | /** |
||
55 | * Calculate the modulo 11 check digit for number |
||
56 | */ |
||
57 | 6 | public function calculateCheckDigit(string $number): string |
|
58 | { |
||
59 | 6 | $this->assertNumber($number); |
|
60 | |||
61 | 1 | $sum = 0; |
|
62 | |||
63 | 1 | View Code Duplication | foreach (array_reverse(str_split($number)) as $pos => $digit) { |
|
|||
64 | 1 | $sum += $digit * $this->getWeight($pos, 2); |
|
65 | } |
||
66 | |||
67 | // Calculate check digit from remainder |
||
68 | 1 | return self::$remainderToCheck[11 - $sum % 11]; |
|
69 | } |
||
70 | |||
71 | /** |
||
72 | * Calculate weight based on position in number |
||
73 | * |
||
74 | * @param int $pos Position in number (starts from 0) |
||
75 | * @param int $start Start value for weight calculation (value of position 0) |
||
76 | */ |
||
77 | 2 | protected function getWeight(int $pos, int $start = 1): int |
|
87 | } |
||
88 |
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.