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 UnrewindableIterator implements Iterator |
||
20 | { |
||
21 | /** @var Generator|null */ |
||
22 | private $iterator; |
||
23 | |||
24 | /** @var bool */ |
||
25 | private $iteratorAdvanced = false; |
||
26 | |||
27 | /** |
||
28 | * Initialize the iterator. This effectively rewinds the Traversable and |
||
29 | * the wrapping Generator, which will execute up to its first yield statement. |
||
30 | * Additionally, this mimics behavior of the SPL iterators and allows users |
||
31 | * to omit an explicit call to rewind() before using the other methods. |
||
32 | */ |
||
33 | 11 | public function __construct(Traversable $iterator) |
|
38 | |||
39 | 3 | public function toArray() : array |
|
53 | |||
54 | /** |
||
55 | * @see http://php.net/iterator.current |
||
56 | * |
||
57 | * @return mixed |
||
58 | */ |
||
59 | 7 | public function current() |
|
63 | |||
64 | /** |
||
65 | * @see http://php.net/iterator.mixed |
||
66 | * |
||
67 | * @return mixed |
||
68 | */ |
||
69 | 9 | public function key() |
|
77 | |||
78 | /** |
||
79 | * @see http://php.net/iterator.next |
||
80 | */ |
||
81 | 5 | public function next() : void |
|
89 | |||
90 | /** |
||
91 | * @see http://php.net/iterator.rewind |
||
92 | */ |
||
93 | 6 | public function rewind() : void |
|
97 | |||
98 | /** |
||
99 | * @see http://php.net/iterator.valid |
||
100 | */ |
||
101 | 9 | public function valid() : bool |
|
105 | |||
106 | 8 | private function preventRewinding(string $method) : void |
|
115 | |||
116 | 7 | private function getIterator() : Generator |
|
124 | |||
125 | 11 | View Code Duplication | private function wrapTraversable(Traversable $traversable) : Generator |
134 | } |
||
135 |
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.