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 |
||
7 | class CacheChain implements iCache |
||
8 | { |
||
9 | /** |
||
10 | * @var Cache[] |
||
11 | */ |
||
12 | private $caches = []; |
||
13 | |||
14 | /** |
||
15 | * __construct |
||
16 | * |
||
17 | * @param array $caches |
||
18 | */ |
||
19 | 1 | public function __construct(array $caches = []) |
|
20 | { |
||
21 | 1 | \array_map( |
|
22 | [ |
||
23 | 1 | $this, |
|
24 | 1 | 'addCache', |
|
25 | ], |
||
26 | 1 | $caches |
|
27 | ); |
||
28 | 1 | } |
|
29 | |||
30 | /** |
||
31 | * get caches |
||
32 | * |
||
33 | * @return array |
||
34 | */ |
||
35 | public function getCaches(): array |
||
39 | |||
40 | /** |
||
41 | * add cache |
||
42 | * |
||
43 | * @param Cache $cache |
||
44 | * @param bool $prepend |
||
45 | */ |
||
46 | 1 | public function addCache(Cache $cache, $prepend = true) |
|
54 | |||
55 | /** |
||
56 | * {@inheritdoc} |
||
57 | */ |
||
58 | public function getItem(string $key) |
||
68 | |||
69 | /** |
||
70 | * Get the "isReady" state. |
||
71 | * |
||
72 | * @return bool |
||
73 | */ |
||
74 | 1 | public function getCacheIsReady(): bool |
|
84 | |||
85 | /** |
||
86 | * {@inheritdoc} |
||
87 | */ |
||
88 | public function setItem(string $key, $value, $ttl = null): bool |
||
99 | |||
100 | /** |
||
101 | * {@inheritdoc} |
||
102 | */ |
||
103 | public function setItemToDate(string $key, $value, \DateTimeInterface $date): bool |
||
114 | |||
115 | /** |
||
116 | * !!! Set the prefix. !!! |
||
117 | * |
||
118 | * WARNING: Do not use if you don't know what you do. Because this will overwrite the default prefix. |
||
119 | * |
||
120 | * @param string $prefix |
||
121 | */ |
||
122 | public function setPrefix(string $prefix) |
||
128 | |||
129 | /** |
||
130 | * {@inheritdoc} |
||
131 | */ |
||
132 | View Code Duplication | public function removeItem(string $key): bool |
|
143 | |||
144 | /** |
||
145 | * {@inheritdoc} |
||
146 | */ |
||
147 | public function existsItem(string $key): bool |
||
157 | |||
158 | /** |
||
159 | * {@inheritdoc} |
||
160 | */ |
||
161 | View Code Duplication | public function removeAll(): bool |
|
172 | } |
||
173 |
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.