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 |
||
27 | class ArraySet extends ArrayCollection implements ArraySetInterface |
||
28 | { |
||
29 | /** |
||
30 | * ArraySet constructor. |
||
31 | * |
||
32 | * @param array $elements |
||
33 | */ |
||
34 | public function __construct(array $elements = array()) |
||
38 | |||
39 | /** |
||
40 | * {@inheritdoc} |
||
41 | */ |
||
42 | public function add($element) |
||
55 | |||
56 | /** |
||
57 | * {@inheritdoc} |
||
58 | */ |
||
59 | public function addAll($elements) |
||
67 | |||
68 | /** |
||
69 | * {@inheritdoc} |
||
70 | */ |
||
71 | View Code Duplication | public function contains($element) |
|
82 | |||
83 | /** |
||
84 | * {@inheritdoc} |
||
85 | */ |
||
86 | public function containsAll($elements) |
||
98 | |||
99 | /** |
||
100 | * {@inheritdoc} |
||
101 | */ |
||
102 | public function remove($element) |
||
103 | { |
||
104 | $criteria = Criteria::eq($element); |
||
105 | foreach ($this->elements as $key => $value) { |
||
106 | if ($criteria->evaluate($value)) { |
||
107 | unset($this->elements[$key]); |
||
108 | $this->elements = array_values($this->elements); |
||
109 | |||
110 | return true; |
||
111 | } |
||
112 | } |
||
113 | |||
114 | return false; |
||
115 | } |
||
116 | |||
117 | /** |
||
118 | * {@inheritdoc} |
||
119 | */ |
||
120 | View Code Duplication | public function removeAll($elements) |
|
133 | |||
134 | /** |
||
135 | * {@inheritdoc} |
||
136 | */ |
||
137 | View Code Duplication | public function sort(ComparatorInterface $criteria = null) |
|
147 | |||
148 | /** |
||
149 | * {@inheritdoc} |
||
150 | */ |
||
151 | public function sorted(ComparatorInterface $criteria) |
||
155 | |||
156 | /** |
||
157 | * {@inheritdoc} |
||
158 | */ |
||
159 | public function find(SpecificationInterface $criteria) |
||
163 | |||
164 | /** |
||
165 | * {@inheritdoc} |
||
166 | */ |
||
167 | public function findOne(SpecificationInterface $criteria) |
||
171 | |||
172 | /** |
||
173 | * {@inheritdoc} |
||
174 | */ |
||
175 | public function offsetSet($offset, $value) |
||
179 | |||
180 | /** |
||
181 | * {@inheritdoc} |
||
182 | */ |
||
183 | protected function validateKey($key) |
||
191 | } |
||
192 |
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.