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 | class CardinalNumeralGenerator extends NumeralGenerator |
||
8 | { |
||
9 | /** |
||
10 | * @var string[] |
||
11 | * @phpstan-var array<int, string> |
||
12 | */ |
||
13 | public static $words = [ |
||
14 | 1 => 'one', |
||
15 | 2 => 'two', |
||
16 | 3 => 'three', |
||
17 | 4 => 'four', |
||
18 | 5 => 'five', |
||
19 | 6 => 'six', |
||
20 | 7 => 'seven', |
||
21 | 8 => 'eight', |
||
22 | 9 => 'nine', |
||
23 | 10 => 'ten', |
||
24 | 11 => 'eleven', |
||
25 | 12 => 'twelve', |
||
26 | 13 => 'thirteen', |
||
27 | 14 => 'fourteen', |
||
28 | 15 => 'fifteen', |
||
29 | 16 => 'sixteen', |
||
30 | 17 => 'seventeen', |
||
31 | 18 => 'eighteen', |
||
32 | 19 => 'nineteen', |
||
33 | 20 => 'twenty', |
||
34 | 30 => 'thirty', |
||
35 | 40 => 'forty', |
||
36 | 50 => 'fifty', |
||
37 | 60 => 'sixty', |
||
38 | 70 => 'seventy', |
||
39 | 80 => 'eighty', |
||
40 | 90 => 'ninety', |
||
41 | ]; |
||
42 | |||
43 | /** |
||
44 | * @var string[] |
||
45 | * @phpstan-var array<int, string> |
||
46 | */ |
||
47 | public static $exponents = [ |
||
48 | 100 => 'hundred', |
||
49 | 1000 => 'thousand', |
||
50 | 1000000 => 'million', |
||
51 | 1000000000 => 'billion', |
||
52 | 1000000000000 => 'trillion', |
||
53 | ]; |
||
54 | |||
55 | public static function getCases($number) |
||
59 | |||
60 | public static function getCase($number, $case) |
||
64 | |||
65 | /** |
||
66 | * @param int $number |
||
67 | * @return mixed|string |
||
68 | */ |
||
69 | 6 | public static function generate($number) |
|
99 | } |
||
100 |
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.