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 |
||
18 | class time extends \Threaded implements \Collectable |
||
19 | { |
||
20 | /** |
||
21 | * @var Message |
||
22 | */ |
||
23 | private $message; |
||
24 | /** |
||
25 | * @var Discord |
||
26 | */ |
||
27 | private $discord; |
||
28 | /** |
||
29 | * @var Logger |
||
30 | */ |
||
31 | private $log; |
||
32 | /** |
||
33 | * @var array |
||
34 | */ |
||
35 | private $channelConfig; |
||
36 | /** |
||
37 | * @var Config |
||
38 | */ |
||
39 | private $config; |
||
40 | /** |
||
41 | * @var Db |
||
42 | */ |
||
43 | private $db; |
||
44 | /** |
||
45 | * @var cURL |
||
46 | */ |
||
47 | private $curl; |
||
48 | /** |
||
49 | * @var Settings |
||
50 | */ |
||
51 | private $settings; |
||
52 | /** |
||
53 | * @var Permissions |
||
54 | */ |
||
55 | private $permissions; |
||
56 | /** |
||
57 | * @var ServerConfig |
||
58 | */ |
||
59 | private $serverConfig; |
||
60 | /** |
||
61 | * @var Users |
||
62 | */ |
||
63 | private $users; |
||
64 | /** |
||
65 | * @var array |
||
66 | */ |
||
67 | private $extras; |
||
68 | |||
69 | View Code Duplication | public function __construct($message, $discord, $channelConfig, $log, $config, $db, $curl, $settings, $permissions, $serverConfig, $users, $extras) |
|
84 | |||
85 | public function run() |
||
108 | } |
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: