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 | 18 | protected function handleRecursively(Event $event) |
|
67 | |||
68 | /** |
||
69 | * @param Event $event |
||
70 | * @return string |
||
71 | */ |
||
72 | 24 | private function getApplyMethod(Event $event) |
|
78 | |||
79 | /** |
||
80 | * @return DomainEventStream |
||
81 | */ |
||
82 | 15 | public function getUncommittedEvents() |
|
90 | |||
91 | /** |
||
92 | * @param DomainEventStream $stream |
||
93 | */ |
||
94 | 6 | public function initializeState(DomainEventStream $stream) |
|
101 | |||
102 | /** |
||
103 | * @param Entity $entity |
||
104 | */ |
||
105 | 6 | public function addChildEntity(Entity $entity) |
|
109 | } |
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: