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 |
||
17 | class CacheAdapter |
||
18 | { |
||
19 | const KEY_VERSION = 1; |
||
20 | const KEY_CHILDREN = 2; |
||
21 | |||
22 | /** |
||
23 | * @var Cache |
||
24 | */ |
||
25 | private $cache; |
||
26 | |||
27 | /** |
||
28 | * @var string |
||
29 | */ |
||
30 | private $childInvalidationConstraint; |
||
31 | |||
32 | /** |
||
33 | * @param Cache $cache |
||
34 | * @param string $childInvalidationConstraint |
||
35 | */ |
||
36 | public function __construct(Cache $cache, $childInvalidationConstraint = '') |
||
41 | |||
42 | /** |
||
43 | * @param string $childInvalidationConstraint |
||
44 | * |
||
45 | * @return $this |
||
46 | */ |
||
47 | public function setChildInvalidationConstraint($childInvalidationConstraint) |
||
53 | |||
54 | /** |
||
55 | * @param Request $request |
||
56 | * |
||
57 | * @return string |
||
58 | */ |
||
59 | public function fetch(Request $request) |
||
67 | |||
68 | /** |
||
69 | * @param Request $request |
||
70 | * |
||
71 | * @return bool |
||
72 | */ |
||
73 | public function contains(Request $request) |
||
77 | |||
78 | /** |
||
79 | * @param string $key |
||
80 | * |
||
81 | * @return bool |
||
82 | */ |
||
83 | public function containsKey($key) |
||
87 | |||
88 | /** |
||
89 | * @param Request $request |
||
90 | * @param string $version |
||
91 | * |
||
92 | * @return mixed |
||
93 | */ |
||
94 | public function update(Request $request, $version) |
||
120 | |||
121 | /** |
||
122 | * @param Request $request |
||
123 | * @param string $version |
||
124 | * |
||
125 | * @return mixed |
||
126 | */ |
||
127 | public function register(Request $request, $version) |
||
152 | |||
153 | private function invalidateChildren(array $children, $version) |
||
170 | |||
171 | /** |
||
172 | * @param Request $request |
||
173 | * |
||
174 | * @return array |
||
175 | */ |
||
176 | private function getSegments(Request $request) |
||
192 | |||
193 | /** |
||
194 | * @param Request $request |
||
195 | * |
||
196 | * @return string |
||
197 | */ |
||
198 | private function createKey(Request $request) |
||
202 | |||
203 | /** |
||
204 | * @param array $segments |
||
205 | * |
||
206 | * @return string |
||
207 | */ |
||
208 | private function createKeyFromSegments(array $segments) |
||
212 | } |
||
213 |
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.