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 |
||
| 15 | abstract class AggregateRoot implements AggregateRootInterface |
||
| 16 | { |
||
| 17 | /** |
||
| 18 | * @var [] |
||
| 19 | */ |
||
| 20 | private $uncommittedEvents = []; |
||
| 21 | |||
| 22 | private $playHead = -1; |
||
| 23 | |||
| 24 | /** @var Entity[] */ |
||
| 25 | private $children = []; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @param Event $event |
||
| 29 | */ |
||
| 30 | 18 | public function apply(Event $event) |
|
| 42 | |||
| 43 | |||
| 44 | /** |
||
| 45 | * Handles event if capable. |
||
| 46 | * |
||
| 47 | * @param $event |
||
| 48 | */ |
||
| 49 | 24 | View Code Duplication | protected function handle(Event $event) |
| 57 | |||
| 58 | /** |
||
| 59 | * @param Event $event |
||
| 60 | */ |
||
| 61 | 18 | protected function handleRecursively(Event $event) |
|
| 70 | |||
| 71 | /** |
||
| 72 | * @param Event $event |
||
| 73 | * @return string |
||
| 74 | */ |
||
| 75 | 24 | private function getApplyMethod(Event $event) |
|
| 81 | |||
| 82 | /** |
||
| 83 | * @return DomainEventStream |
||
| 84 | */ |
||
| 85 | 15 | public function getUncommittedEvents() |
|
| 93 | |||
| 94 | /** |
||
| 95 | * @param DomainEventStream $stream |
||
| 96 | */ |
||
| 97 | 6 | public function initializeState(DomainEventStream $stream) |
|
| 104 | |||
| 105 | /** |
||
| 106 | * @param Entity $entity |
||
| 107 | */ |
||
| 108 | 6 | public function addChildEntity(Entity $entity) |
|
| 112 | } |
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: