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 |
||
28 | class ArrayStore implements SortableStore, CountableStore |
||
29 | { |
||
30 | /** |
||
31 | * Flag: Enable serialization. |
||
32 | */ |
||
33 | const SERIALIZE = 1; |
||
34 | |||
35 | /** |
||
36 | * @var array |
||
37 | */ |
||
38 | private $array = array(); |
||
39 | |||
40 | /** |
||
41 | * @var callable |
||
42 | */ |
||
43 | private $serialize; |
||
44 | |||
45 | /** |
||
46 | * @var callable |
||
47 | */ |
||
48 | private $unserialize; |
||
49 | |||
50 | /** |
||
51 | * Creates a new store. |
||
52 | * |
||
53 | * @param array $array The values to set initially in the store. |
||
54 | */ |
||
55 | 192 | public function __construct(array $array = array(), $flags = 0) |
|
75 | |||
76 | /** |
||
77 | * {@inheritdoc} |
||
78 | */ |
||
79 | 132 | public function set($key, $value) |
|
85 | |||
86 | /** |
||
87 | * {@inheritdoc} |
||
88 | */ |
||
89 | 12 | View Code Duplication | public function get($key, $default = null) |
99 | |||
100 | /** |
||
101 | * {@inheritdoc} |
||
102 | */ |
||
103 | 60 | View Code Duplication | public function getOrFail($key) |
113 | |||
114 | /** |
||
115 | * {@inheritdoc} |
||
116 | */ |
||
117 | 80 | public function getMultiple(array $keys, $default = null) |
|
131 | |||
132 | /** |
||
133 | * {@inheritdoc} |
||
134 | */ |
||
135 | 60 | public function getMultipleOrFail(array $keys) |
|
147 | |||
148 | /** |
||
149 | * {@inheritdoc} |
||
150 | */ |
||
151 | 20 | public function remove($key) |
|
161 | |||
162 | /** |
||
163 | * {@inheritdoc} |
||
164 | */ |
||
165 | 60 | public function exists($key) |
|
171 | |||
172 | /** |
||
173 | * {@inheritdoc} |
||
174 | */ |
||
175 | 186 | public function clear() |
|
179 | |||
180 | /** |
||
181 | * {@inheritdoc} |
||
182 | */ |
||
183 | 24 | public function keys() |
|
187 | |||
188 | /** |
||
189 | * Returns the contents of the store as array. |
||
190 | * |
||
191 | * @return array The keys and values in the store. |
||
192 | */ |
||
193 | public function toArray() |
||
197 | |||
198 | /** |
||
199 | * {@inheritdoc} |
||
200 | */ |
||
201 | 12 | public function sort($flags = SORT_REGULAR) |
|
205 | |||
206 | /** |
||
207 | * {@inheritdoc} |
||
208 | */ |
||
209 | 2 | public function count() |
|
213 | } |
||
214 |
Let’s take a look at an example: