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 |
||
6 | class GeneratorContainer |
||
7 | { |
||
8 | /** |
||
9 | * Generator. |
||
10 | * @var \Generator |
||
11 | */ |
||
12 | private $g; |
||
13 | |||
14 | /** |
||
15 | * Generator object hash. |
||
16 | * @var string |
||
17 | */ |
||
18 | private $h; |
||
19 | |||
20 | /** |
||
21 | * Thrown exception. |
||
22 | * @var \RuntimeException |
||
23 | */ |
||
24 | private $e; |
||
25 | |||
26 | /** |
||
27 | * Parent yield key. |
||
28 | * @var mixed |
||
29 | */ |
||
30 | private $yieldKey; |
||
31 | |||
32 | /** |
||
33 | * Constructor. |
||
34 | * @param \Generator $g |
||
35 | */ |
||
36 | 42 | public function __construct(\Generator $g, $yield_key = null) |
|
43 | |||
44 | /** |
||
45 | * Return parent yield key. |
||
46 | * @return mixed |
||
47 | */ |
||
48 | 27 | public function getYieldKey() |
|
52 | |||
53 | /** |
||
54 | * Return generator hash. |
||
55 | * @return string |
||
56 | */ |
||
57 | 28 | public function __toString() |
|
61 | |||
62 | /** |
||
63 | * Return whether generator is actually working. |
||
64 | * @return bool |
||
65 | */ |
||
66 | 42 | public function valid() |
|
75 | |||
76 | /** |
||
77 | * Return current key. |
||
78 | * @return mixed |
||
79 | */ |
||
80 | 32 | public function key() |
|
85 | |||
86 | /** |
||
87 | * Return current value. |
||
88 | * @return mixed |
||
89 | */ |
||
90 | 34 | public function current() |
|
95 | |||
96 | /** |
||
97 | * Send value into generator. |
||
98 | * @param mixed $value |
||
99 | * @NOTE: This method returns nothing, |
||
100 | * while original generator returns something. |
||
101 | */ |
||
102 | 30 | View Code Duplication | public function send($value) |
111 | |||
112 | /** |
||
113 | * Throw exception into generator. |
||
114 | * @param \Throwable|\RuntimeException $e |
||
115 | * @NOTE: This method returns nothing, |
||
116 | * while original generator returns something. |
||
117 | */ |
||
118 | 19 | View Code Duplication | public function throw_($e) |
127 | |||
128 | /** |
||
129 | * Return whether Throwable is thrown. |
||
130 | * @return bool |
||
131 | */ |
||
132 | 30 | public function thrown() |
|
136 | |||
137 | /** |
||
138 | * Return value that generator has returned or thrown. |
||
139 | * @return mixed |
||
140 | */ |
||
141 | 33 | public function getReturnOrThrown() |
|
152 | |||
153 | /** |
||
154 | * Validate that generator has finished running. |
||
155 | * @throws LogicException |
||
156 | */ |
||
157 | 35 | private function validateValidity() |
|
163 | |||
164 | /** |
||
165 | * Validate that generator is still running. |
||
166 | * @throws LogicException |
||
167 | */ |
||
168 | 33 | private function validateInvalidity() |
|
174 | } |
||
175 |