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 |
||
12 | class Collection implements CollectionInterface |
||
13 | { |
||
14 | /** |
||
15 | * @var array |
||
16 | */ |
||
17 | public $collection = []; |
||
18 | |||
19 | /** |
||
20 | * If $data is passed, populate collection |
||
21 | * |
||
22 | * @param $data array |
||
23 | * |
||
24 | * @access public |
||
25 | */ |
||
26 | 16 | public function __construct(array $data = []) |
|
30 | |||
31 | 1 | public function count() : int |
|
35 | |||
36 | 3 | public function isEmpty() : bool |
|
44 | |||
45 | 4 | public function getArray() : array |
|
49 | |||
50 | 1 | public function jsonSerialize() : array //@TODO: this should return text i think (wrong) |
|
54 | |||
55 | 1 | public function getIterator() : \ArrayIterator |
|
59 | |||
60 | 3 | public function offsetExists($offset) |
|
64 | |||
65 | 1 | public function offsetGet($offset) |
|
69 | |||
70 | 1 | public function offsetSet($offset, $value) |
|
74 | |||
75 | 1 | public function offsetUnset($offset) |
|
81 | |||
82 | 4 | public function clear() |
|
86 | |||
87 | 1 | View Code Duplication | public function map(callable $func) |
|
|||
88 | { |
||
89 | 1 | $result = []; |
|
90 | |||
91 | 1 | foreach ($this->collection as $key => $item) { |
|
92 | 1 | $result[$key] = $func($item); |
|
93 | } |
||
94 | |||
95 | 1 | $this->clear(); |
|
96 | 1 | $this->collection = $result; |
|
97 | 1 | } |
|
98 | |||
99 | 1 | View Code Duplication | public function filter(callable $func) |
112 | |||
113 | 1 | public function each(callable $func) |
|
121 | |||
122 | 1 | View Code Duplication | public function not(callable $func) |
135 | |||
136 | 2 | public function reduce($initial, callable $func) |
|
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.