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 AgeRange |
||
8 | { |
||
9 | /** |
||
10 | * @var null|Age |
||
11 | */ |
||
12 | private $from; |
||
13 | |||
14 | /** |
||
15 | * @var null|Age |
||
16 | */ |
||
17 | private $to; |
||
18 | |||
19 | /** |
||
20 | * AgeRange constructor. |
||
21 | * @param null|Age $from |
||
22 | * @param null|Age $to |
||
23 | */ |
||
24 | public function __construct(Age $from = null, Age $to = null) |
||
31 | |||
32 | /** |
||
33 | * @param null|Age $from |
||
34 | * @param null|Age $to |
||
35 | * |
||
36 | * @throws InvalidAgeRangeException |
||
37 | */ |
||
38 | private function guardValidAgeRange(Age $from = null, Age $to = null) |
||
44 | |||
45 | /** |
||
46 | * @return null|Age |
||
47 | */ |
||
48 | public function getFrom() |
||
52 | |||
53 | /** |
||
54 | * @return null|Age |
||
55 | */ |
||
56 | public function getTo() |
||
60 | |||
61 | /** |
||
62 | * @return string |
||
63 | */ |
||
64 | public function __toString() |
||
71 | |||
72 | /** |
||
73 | * @param string $ageRangeString |
||
74 | * @return AgeRange |
||
75 | * |
||
76 | * @throws InvalidAgeRangeException |
||
77 | */ |
||
78 | public static function fromString($ageRangeString) |
||
121 | |||
122 | /** |
||
123 | * @param AgeRange $otherAgeRange |
||
124 | * @return bool |
||
125 | */ |
||
126 | public function sameAs(AgeRange $otherAgeRange) |
||
130 | } |
||
131 |
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.