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 |
||
20 | View Code Duplication | class CardinalityAggregation extends AbstractAggregation |
|
|
|||
21 | { |
||
22 | use MetricTrait; |
||
23 | use ScriptAwareTrait; |
||
24 | |||
25 | /** |
||
26 | * @var int |
||
27 | */ |
||
28 | private $precisionThreshold; |
||
29 | |||
30 | /** |
||
31 | * @var bool |
||
32 | */ |
||
33 | private $rehash; |
||
34 | |||
35 | /** |
||
36 | * {@inheritdoc} |
||
37 | */ |
||
38 | public function getArray() |
||
39 | { |
||
40 | $out = array_filter( |
||
41 | [ |
||
42 | 'field' => $this->getField(), |
||
43 | 'script' => $this->getScript(), |
||
44 | 'precision_threshold' => $this->getPrecisionThreshold(), |
||
45 | 'rehash' => $this->isRehash(), |
||
46 | ], |
||
47 | function ($val) { |
||
48 | return ($val || is_bool($val)); |
||
49 | } |
||
50 | ); |
||
51 | |||
52 | $this->checkRequiredFields($out); |
||
53 | |||
54 | return $out; |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * Precision threshold. |
||
59 | * |
||
60 | * @param int $precision Precision Threshold. |
||
61 | */ |
||
62 | public function setPrecisionThreshold($precision) |
||
66 | |||
67 | /** |
||
68 | * @return int |
||
69 | */ |
||
70 | public function getPrecisionThreshold() |
||
74 | |||
75 | /** |
||
76 | * @return bool |
||
77 | */ |
||
78 | public function isRehash() |
||
82 | |||
83 | /** |
||
84 | * @param bool $rehash |
||
85 | */ |
||
86 | public function setRehash($rehash) |
||
90 | |||
91 | /** |
||
92 | * {@inheritdoc} |
||
93 | */ |
||
94 | public function getType() |
||
98 | |||
99 | /** |
||
100 | * Checks if required fields are set. |
||
101 | * |
||
102 | * @param array $fields |
||
103 | * |
||
104 | * @throws \LogicException |
||
105 | */ |
||
106 | private function checkRequiredFields($fields) |
||
112 | } |
||
113 |
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.