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