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 |
||
| 27 | class PasswordRepository implements PasswordRepositoryInterface |
||
| 28 | { |
||
| 29 | const EXPIRED_PASSWORDS_PURGE_SIZE = 60000; |
||
| 30 | |||
| 31 | /** |
||
| 32 | * @var PasswordFactory |
||
| 33 | */ |
||
| 34 | private $passwordFactory; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @var PasswordResource |
||
| 38 | */ |
||
| 39 | private $passwordResource; |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @var CollectionFactory |
||
| 43 | */ |
||
| 44 | private $collectionFactory; |
||
| 45 | |||
| 46 | /** |
||
| 47 | * PasswordRepository constructor. |
||
| 48 | * @param PasswordFactory $passwordFactory |
||
| 49 | * @param PasswordResource $passwordResource |
||
| 50 | * @param CollectionFactory $collectionFactory |
||
| 51 | */ |
||
| 52 | public function __construct( |
||
| 61 | |||
| 62 | /** |
||
| 63 | * @param int $customerId |
||
| 64 | * @return PasswordInterface |
||
| 65 | * @throws NoSuchEntityException |
||
| 66 | */ |
||
| 67 | View Code Duplication | public function getByCustomerId(int $customerId): PasswordInterface |
|
| 77 | |||
| 78 | /** |
||
| 79 | * @param PasswordInterface $password |
||
| 80 | * @return void |
||
| 81 | * @throws Exception |
||
| 82 | */ |
||
| 83 | public function save(PasswordInterface $password): void |
||
| 97 | |||
| 98 | /** |
||
| 99 | * @param PasswordInterface $password |
||
| 100 | * @return void |
||
| 101 | * @throws Exception |
||
| 102 | */ |
||
| 103 | View Code Duplication | public function delete(PasswordInterface $password): void |
|
| 114 | |||
| 115 | /** |
||
| 116 | * @param string $dateTime |
||
| 117 | * @return PasswordInterface[] |
||
| 118 | */ |
||
| 119 | public function getOlderThan(string $dateTime): array |
||
| 132 | } |
||
| 133 |
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: