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 |
||
22 | class CargoRoutingDto |
||
23 | { |
||
24 | /** |
||
25 | * @var string |
||
26 | */ |
||
27 | private $trackingId; |
||
28 | |||
29 | /** |
||
30 | * @var string |
||
31 | */ |
||
32 | private $origin; |
||
33 | |||
34 | /** |
||
35 | * @var string |
||
36 | */ |
||
37 | private $finalDestination; |
||
38 | |||
39 | /** |
||
40 | * @var LegDto[] |
||
41 | */ |
||
42 | private $legs = array(); |
||
43 | |||
44 | /** |
||
45 | * @param string $finalDestination |
||
46 | */ |
||
47 | public function setFinalDestination(string $finalDestination) |
||
48 | { |
||
49 | \Assert\that($finalDestination)->notEmpty()->string(); |
||
50 | |||
51 | $this->finalDestination = $finalDestination; |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * @return string |
||
56 | */ |
||
57 | public function getFinalDestination(): string |
||
61 | |||
62 | /** |
||
63 | * @param LegDto[] $legs |
||
64 | */ |
||
65 | public function setLegs(array $legs): array |
||
66 | { |
||
67 | foreach($legs as $leg) { |
||
68 | Assertion::isInstanceOf($leg, LegDto::class); |
||
69 | } |
||
70 | |||
71 | $this->legs = $legs; |
||
72 | } |
||
73 | |||
74 | public function addLeg(LegDto $leg) |
||
78 | |||
79 | /** |
||
80 | * @return LegDto[] |
||
81 | */ |
||
82 | public function getLegs(): array |
||
86 | |||
87 | /** |
||
88 | * @param string $origin |
||
89 | */ |
||
90 | public function setOrigin(string $origin) |
||
91 | { |
||
92 | Assertion::notEmpty($origin); |
||
93 | |||
94 | $this->origin = $origin; |
||
95 | } |
||
96 | |||
97 | /** |
||
98 | * @return string |
||
99 | */ |
||
100 | public function getOrigin() |
||
104 | |||
105 | /** |
||
106 | * @param string $trackingId |
||
107 | */ |
||
108 | public function setTrackingId(string $trackingId) |
||
109 | { |
||
110 | Assertion::uuid($trackingId); |
||
111 | |||
112 | $this->trackingId = $trackingId; |
||
113 | } |
||
114 | |||
115 | /** |
||
116 | * @return string |
||
117 | */ |
||
118 | public function getTrackingId(): string |
||
122 | |||
123 | /** |
||
124 | * @return array |
||
125 | */ |
||
126 | public function getArrayCopy(): array |
||
146 | } |
||
147 |
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.