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 |
||
11 | class PrimeFactors extends Combinatorics implements IteratorInterface |
||
12 | { |
||
13 | /** |
||
14 | * The number. |
||
15 | * |
||
16 | * @var int |
||
17 | */ |
||
18 | protected $number; |
||
19 | |||
20 | /** |
||
21 | * The key. |
||
22 | * |
||
23 | * @var int |
||
24 | */ |
||
25 | protected $key; |
||
26 | |||
27 | /** |
||
28 | * The prime factors. |
||
29 | * |
||
30 | * @var int[] |
||
31 | */ |
||
32 | protected $factors; |
||
33 | |||
34 | /** |
||
35 | * {@inheritdoc} |
||
36 | */ |
||
37 | 6 | public function current() |
|
41 | |||
42 | /** |
||
43 | * {@inheritdoc} |
||
44 | */ |
||
45 | 6 | public function next() |
|
50 | |||
51 | /** |
||
52 | * {@inheritdoc} |
||
53 | */ |
||
54 | 6 | public function valid() |
|
58 | |||
59 | /** |
||
60 | * {@inheritdoc} |
||
61 | */ |
||
62 | 6 | public function rewind() |
|
66 | |||
67 | /** |
||
68 | * Count elements of an object. |
||
69 | * |
||
70 | * @return int |
||
71 | * The number of element |
||
72 | */ |
||
73 | 6 | public function count() |
|
77 | |||
78 | /** |
||
79 | * Set the number. |
||
80 | * |
||
81 | * @param int $number |
||
82 | * The number |
||
83 | */ |
||
84 | 6 | public function setNumber($number) |
|
89 | |||
90 | /** |
||
91 | * Get the number. |
||
92 | * |
||
93 | * @return int |
||
94 | * The number |
||
95 | */ |
||
96 | 6 | public function getNumber() |
|
100 | |||
101 | /** |
||
102 | * Compute the prime factors of the number. |
||
103 | * |
||
104 | * @param mixed $number |
||
105 | * |
||
106 | * @return int[] |
||
107 | * The factors |
||
108 | */ |
||
109 | 6 | private function getFactors($number) |
|
126 | } |
||
127 |
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.