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 |
||
19 | final class BaseIterator implements Iterator |
||
20 | { |
||
21 | private $key; |
||
22 | |||
23 | private $current; |
||
24 | |||
25 | /** @var Generator */ |
||
26 | private $iterator; |
||
27 | |||
28 | /** @var bool */ |
||
29 | private $iteratorAdvanced = false; |
||
30 | |||
31 | /** |
||
32 | * Initialize the iterator and stores the first item in the cache. This |
||
33 | * effectively rewinds the Traversable and the wrapping Generator, which |
||
34 | * will execute up to its first yield statement. Additionally, this mimics |
||
35 | * behavior of the SPL iterators and allows users to omit an explicit call |
||
36 | * to rewind() before using the other methods. |
||
37 | */ |
||
38 | 7 | public function __construct(Traversable $iterator) |
|
43 | |||
44 | 2 | public function toArray() : array |
|
60 | |||
61 | /** |
||
62 | * @see http://php.net/iterator.current |
||
63 | * |
||
64 | * @return mixed |
||
65 | */ |
||
66 | 5 | public function current() |
|
70 | |||
71 | /** |
||
72 | * @see http://php.net/iterator.mixed |
||
73 | * |
||
74 | * @return mixed |
||
75 | */ |
||
76 | 5 | public function key() |
|
80 | |||
81 | /** |
||
82 | * @see http://php.net/iterator.next |
||
83 | */ |
||
84 | 4 | public function next() : void |
|
90 | |||
91 | /** |
||
92 | * @see http://php.net/iterator.rewind |
||
93 | */ |
||
94 | 5 | public function rewind() : void |
|
106 | |||
107 | /** |
||
108 | * @see http://php.net/iterator.valid |
||
109 | */ |
||
110 | 6 | public function valid() : bool |
|
114 | |||
115 | /** |
||
116 | * Stores the current item in the cache. |
||
117 | */ |
||
118 | 7 | private function storeCurrentItem() : void |
|
128 | |||
129 | 7 | private function wrapTraversable(Traversable $traversable) : Generator |
|
142 | } |
||
143 |
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.