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 |
||
| 16 | class user extends \Threaded implements \Collectable |
||
| 17 | { |
||
| 18 | /** |
||
| 19 | * @var Message |
||
| 20 | */ |
||
| 21 | private $message; |
||
| 22 | /** |
||
| 23 | * @var Discord |
||
| 24 | */ |
||
| 25 | private $discord; |
||
| 26 | /** |
||
| 27 | * @var Logger |
||
| 28 | */ |
||
| 29 | private $log; |
||
| 30 | /** |
||
| 31 | * @var array |
||
| 32 | */ |
||
| 33 | private $channelConfig; |
||
| 34 | /** |
||
| 35 | * @var Config |
||
| 36 | */ |
||
| 37 | private $config; |
||
| 38 | /** |
||
| 39 | * @var Db |
||
| 40 | */ |
||
| 41 | private $db; |
||
| 42 | /** |
||
| 43 | * @var cURL |
||
| 44 | */ |
||
| 45 | private $curl; |
||
| 46 | /** |
||
| 47 | * @var Settings |
||
| 48 | */ |
||
| 49 | private $settings; |
||
| 50 | /** |
||
| 51 | * @var Permissions |
||
| 52 | */ |
||
| 53 | private $permissions; |
||
| 54 | /** |
||
| 55 | * @var ServerConfig |
||
| 56 | */ |
||
| 57 | private $serverConfig; |
||
| 58 | /** |
||
| 59 | * @var Users |
||
| 60 | */ |
||
| 61 | private $users; |
||
| 62 | /** |
||
| 63 | * @var array |
||
| 64 | */ |
||
| 65 | private $extras; |
||
| 66 | |||
| 67 | View Code Duplication | public function __construct($message, $discord, $channelConfig, $log, $config, $db, $curl, $settings, $permissions, $serverConfig, $users, $extras) |
|
| 82 | |||
| 83 | public function run() |
||
| 109 | } |
Let’s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let’s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare 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.phpHowever, as
OtherDir/Foo.phpdoes 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: