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 |
||
10 | View Code Duplication | class ServerUptime extends Base |
|
11 | { |
||
12 | use Database; |
||
13 | |||
14 | /** |
||
15 | * Check resource. |
||
16 | * |
||
17 | * @return Result |
||
18 | */ |
||
19 | 1 | public function check() |
|
36 | |||
37 | /** |
||
38 | * Execute command to get an uptime string. |
||
39 | * |
||
40 | * @return mixed|string |
||
41 | * @throws Exception |
||
42 | */ |
||
43 | 1 | private function executeUptimeCommand() |
|
55 | |||
56 | /** |
||
57 | * Get current uptime. |
||
58 | * |
||
59 | * @return array |
||
60 | * @throws Exception |
||
61 | */ |
||
62 | 1 | protected function getCurrentUptime() |
|
66 | |||
67 | /** |
||
68 | * Normalize uptime matches. |
||
69 | * |
||
70 | * @param $matches |
||
71 | * @return \Illuminate\Support\Collection |
||
72 | */ |
||
73 | 1 | protected function normalizeMatches($matches) |
|
94 | |||
95 | /** |
||
96 | * Parse the uptime string. |
||
97 | * |
||
98 | * @param $system_string |
||
99 | * @return array |
||
100 | */ |
||
101 | 1 | protected function parseUptimeString($system_string) |
|
118 | |||
119 | /** |
||
120 | * Convert uptime to seconds. |
||
121 | * |
||
122 | * @param $date |
||
123 | * @return int |
||
124 | */ |
||
125 | 1 | protected function uptimeInSeconds($date) |
|
133 | |||
134 | /** |
||
135 | * Make uptime message. |
||
136 | * |
||
137 | * @param $current |
||
138 | * @param $saved |
||
139 | * @return string |
||
140 | */ |
||
141 | 1 | protected function makeMessage($current, $saved = null) |
|
149 | |||
150 | /** |
||
151 | * Convert uptime to human readable string. |
||
152 | * |
||
153 | * @param $uptime |
||
154 | * @return string |
||
155 | */ |
||
156 | 1 | public function toUptimeString($uptime) |
|
164 | } |
||
165 |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: