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 |
||
6 | class Classroom |
||
7 | { |
||
8 | use ClassroomTrait; |
||
9 | |||
10 | /** @var string */ |
||
11 | private $startTime; |
||
12 | |||
13 | /** @var int */ |
||
14 | private $duration; |
||
15 | |||
16 | /** @var int */ |
||
17 | private $extendDuration; |
||
18 | |||
19 | /** @var string */ |
||
20 | private $timeZone; |
||
21 | |||
22 | /** |
||
23 | * @param string $title |
||
24 | * @param \DateTime $startTime |
||
25 | */ |
||
26 | 13 | private function __construct($title, \DateTime $startTime) |
|
31 | |||
32 | /** |
||
33 | * @param string $title |
||
34 | * @param \DateTime $startTime |
||
35 | * @return self |
||
36 | */ |
||
37 | 13 | public static function build($title, \DateTime $startTime) |
|
41 | |||
42 | /** |
||
43 | * @param int $value |
||
44 | * @return self |
||
45 | */ |
||
46 | 1 | public function withDuration($value) |
|
53 | |||
54 | /** |
||
55 | * @param int $value |
||
56 | * @return self |
||
57 | */ |
||
58 | 1 | public function withExtendDuration($value) |
|
65 | |||
66 | /** |
||
67 | * @param string $value |
||
68 | * @return self |
||
69 | */ |
||
70 | 1 | public function withTimeZone($value) |
|
77 | |||
78 | /** |
||
79 | * @return array |
||
80 | */ |
||
81 | 12 | public function toArray() |
|
111 | } |
||
112 |
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.