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 DateRangeAggregation extends AbstractAggregation |
||
23 | { |
||
24 | use BucketingTrait; |
||
25 | |||
26 | /** |
||
27 | * @var string |
||
28 | */ |
||
29 | private $format; |
||
30 | |||
31 | /** |
||
32 | * @return string |
||
33 | */ |
||
34 | public function getFormat() |
||
38 | |||
39 | /** |
||
40 | * @param string $name |
||
41 | * @param string $field |
||
42 | * @param string $format |
||
43 | * @param array $ranges |
||
44 | */ |
||
45 | View Code Duplication | public function __construct($name, $field = null, $format = null, array $ranges = []) |
|
58 | |||
59 | /** |
||
60 | * @param string $format |
||
61 | */ |
||
62 | public function setFormat($format) |
||
66 | |||
67 | /** |
||
68 | * @var array |
||
69 | */ |
||
70 | private $ranges = []; |
||
71 | |||
72 | /** |
||
73 | * Add range to aggregation. |
||
74 | * |
||
75 | * @param string|null $from |
||
76 | * @param string|null $to |
||
77 | * |
||
78 | * @return $this |
||
79 | * |
||
80 | * @throws \LogicException |
||
81 | */ |
||
82 | public function addRange($from = null, $to = null, $key = null) |
||
83 | { |
||
84 | $range = array_filter( |
||
85 | [ |
||
86 | 'from' => $from, |
||
87 | 'to' => $to, |
||
88 | 'key' => $key, |
||
89 | ] |
||
90 | ); |
||
91 | |||
92 | if (empty($range)) { |
||
93 | throw new \LogicException('Either from or to must be set. Both cannot be null.'); |
||
94 | } |
||
95 | |||
96 | $this->ranges[] = $range; |
||
97 | |||
98 | return $this; |
||
99 | } |
||
100 | |||
101 | /** |
||
102 | * {@inheritdoc} |
||
103 | */ |
||
104 | public function getArray() |
||
117 | |||
118 | /** |
||
119 | * {@inheritdoc} |
||
120 | */ |
||
121 | public function getType() |
||
125 | } |
||
126 |
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.