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 |
||
28 | final class InMemoryUserRepository implements UserRepository |
||
29 | { |
||
30 | /** |
||
31 | * Array which contains the users. |
||
32 | * |
||
33 | * @var array |
||
34 | */ |
||
35 | private $users; |
||
36 | |||
37 | /** |
||
38 | * The user event bus, it can be null |
||
39 | * |
||
40 | * @var UserEventBus|null |
||
41 | */ |
||
42 | private $eventBus; |
||
43 | |||
44 | /** |
||
45 | * Constructor. |
||
46 | * |
||
47 | * @param UserEventBus|null $anEventBus The user event bus, it can be null |
||
48 | */ |
||
49 | public function __construct(UserEventBus $anEventBus = null) |
||
54 | |||
55 | /** |
||
56 | * {@inheritdoc} |
||
57 | */ |
||
58 | public function userOfId(UserId $anId) |
||
64 | |||
65 | /** |
||
66 | * {@inheritdoc} |
||
67 | */ |
||
68 | public function userOfEmail(UserEmail $anEmail) |
||
76 | |||
77 | /** |
||
78 | * {@inheritdoc} |
||
79 | */ |
||
80 | public function userOfConfirmationToken(UserToken $aConfirmationToken) |
||
88 | |||
89 | /** |
||
90 | * {@inheritdoc} |
||
91 | */ |
||
92 | public function userOfInvitationToken(UserToken $anInvitationToken) |
||
100 | |||
101 | /** |
||
102 | * {@inheritdoc} |
||
103 | */ |
||
104 | public function userOfRememberPasswordToken(UserToken $aRememberPasswordToken) |
||
112 | |||
113 | /** |
||
114 | * {@inheritdoc} |
||
115 | */ |
||
116 | View Code Duplication | public function persist(User $aUser) |
|
|
|||
117 | { |
||
118 | $this->users[$aUser->id()->id()] = $aUser; |
||
119 | |||
120 | if ($this->eventBus instanceof UserEventBus) { |
||
121 | $this->handle($aUser->events()); |
||
122 | } |
||
123 | } |
||
124 | |||
125 | /** |
||
126 | * {@inheritdoc} |
||
127 | */ |
||
128 | View Code Duplication | public function remove(User $aUser) |
|
129 | { |
||
130 | unset($this->users[$aUser->id()->id()]); |
||
131 | |||
132 | if ($this->eventBus instanceof UserEventBus) { |
||
133 | $this->handle($aUser->events()); |
||
134 | } |
||
135 | } |
||
136 | |||
137 | /** |
||
138 | * {@inheritdoc} |
||
139 | */ |
||
140 | public function size() |
||
144 | |||
145 | /** |
||
146 | * Handles the given events with event bus. |
||
147 | * |
||
148 | * @param array $events A collection of user domain events |
||
149 | */ |
||
150 | private function handle($events) |
||
156 | } |
||
157 |
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.