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 |
||
15 | class File extends Storage |
||
16 | { |
||
17 | /** |
||
18 | * The path to which the cache files should be written. |
||
19 | * |
||
20 | * @var string |
||
21 | */ |
||
22 | protected $path; |
||
23 | |||
24 | /** |
||
25 | * @param $path |
||
26 | */ |
||
27 | public function __construct($path) |
||
31 | |||
32 | /** |
||
33 | * Determine if an item exists in the cache. |
||
34 | * |
||
35 | * @param $key |
||
36 | * |
||
37 | * @return bool |
||
38 | */ |
||
39 | public function has($key) |
||
43 | |||
44 | /** |
||
45 | * @param string $key |
||
46 | * |
||
47 | * @return bool|mixed|null |
||
48 | */ |
||
49 | View Code Duplication | protected function retrieve($key) |
|
65 | |||
66 | /** |
||
67 | * Write an item to the cache for a given number of minutes. |
||
68 | * |
||
69 | * <code> |
||
70 | * // Put an item in the cache for 15 minutes |
||
71 | * Cache::put('name', 'Robin', 15); |
||
72 | * </code> |
||
73 | * |
||
74 | * @param string $key |
||
75 | * @param mixed $value |
||
76 | * @param int $minutes |
||
77 | * |
||
78 | * @return int|void |
||
79 | */ |
||
80 | public function put($key, $value, $minutes) |
||
90 | |||
91 | /** |
||
92 | * Write an item to the cache for five years. |
||
93 | * |
||
94 | * @param $key |
||
95 | * @param $value |
||
96 | * |
||
97 | * @return int|void |
||
98 | */ |
||
99 | public function forever($key, $value) |
||
103 | |||
104 | /** |
||
105 | * Delete an item from the cache. |
||
106 | * |
||
107 | * @param string $key |
||
108 | * |
||
109 | * @return bool |
||
110 | */ |
||
111 | public function forget($key) |
||
124 | } |
||
125 |
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.