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 |
||
15 | class NodeCollection extends Collection implements NodeCollectionInterface |
||
16 | { |
||
17 | /** |
||
18 | * {@inheritdoc} |
||
19 | */ |
||
20 | 9 | public function add($value) |
|
27 | |||
28 | /** |
||
29 | * {@inheritdoc} |
||
30 | */ |
||
31 | 2 | public function apply($fn) |
|
32 | { |
||
33 | 2 | foreach ($this->items as &$item) { |
|
34 | 2 | $out = call_user_func($fn, $item); |
|
35 | 1 | if (isset($out) && ($out instanceof NodeInterface)) { |
|
36 | 1 | $item = $out; |
|
37 | } |
||
38 | } |
||
39 | |||
40 | 1 | return $this; |
|
41 | } |
||
42 | |||
43 | /** |
||
44 | * On clone, clone all flows too |
||
45 | */ |
||
46 | public function __clone() |
||
47 | { |
||
48 | foreach ($this->items as &$item) { |
||
49 | $item = clone $item; |
||
50 | } |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * @return string |
||
55 | */ |
||
56 | public function __toString() |
||
60 | |||
61 | /** |
||
62 | * @inheritdoc |
||
63 | */ |
||
64 | public function getClone() |
||
68 | |||
69 | /** |
||
70 | * @param callable $fn |
||
71 | * @param mixed|null $default |
||
72 | * |
||
73 | * @return NodeInterface|null |
||
74 | */ |
||
75 | 3 | View Code Duplication | public function first(callable $fn = null, $default = null) |
89 | |||
90 | /** |
||
91 | * @param callable $fn |
||
92 | * @param mixed|null $default |
||
93 | * |
||
94 | * @return NodeInterface|null |
||
95 | */ |
||
96 | 2 | View Code Duplication | public function last(callable $fn = null, $default = null) |
110 | } |
||
111 |
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.