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 | /** |
||
25 | * @param Event $event |
||
26 | */ |
||
27 | 18 | public function apply(Event $event) |
|
28 | { |
||
29 | 18 | $this->handleRecursively($event); |
|
30 | |||
31 | 18 | $this->playHead++; |
|
32 | 18 | $this->uncommittedEvents[] = DomainMessage::recordNow( |
|
33 | 18 | $this->getAggregateRootId(), |
|
34 | 18 | $this->playHead, |
|
35 | 18 | new Metadata(array()), |
|
36 | $event |
||
37 | 18 | ); |
|
38 | 18 | } |
|
39 | |||
40 | |||
41 | /** |
||
42 | * Handles event if capable. |
||
43 | * |
||
44 | * @param $event |
||
45 | */ |
||
46 | 24 | View Code Duplication | protected function handle(Event $event) |
|
|||
47 | { |
||
48 | 24 | $method = $this->getApplyMethod($event); |
|
49 | 24 | if (!method_exists($this, $method)) { |
|
50 | 18 | return; |
|
51 | } |
||
52 | 6 | $this->$method($event); |
|
53 | 6 | } |
|
54 | |||
55 | /** |
||
56 | * @param 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 | * @return EntityInterface[] $entity |
||
104 | */ |
||
105 | 9 | public function getChildren() |
|
109 | } |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.