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 |
||
5 | class StateMachine |
||
6 | { |
||
7 | /** @var StateConfiguration */ |
||
8 | private $currentState; |
||
9 | |||
10 | /** @var StateConfiguration[] */ |
||
11 | private $states = []; |
||
12 | |||
13 | /** @var callable|null */ |
||
14 | private $changeCallback; |
||
15 | |||
16 | /** |
||
17 | * @param string|int|callable $initialState |
||
18 | * @param callable|null $changeCallback f($newState, $event, $oldState, $isSubState, $data) |
||
19 | */ |
||
20 | public function __construct($initialState, $changeCallback = null) |
||
26 | |||
27 | /** |
||
28 | * @param string|int $state |
||
29 | * |
||
30 | * @return StateConfiguration |
||
31 | */ |
||
32 | public function configure($state) |
||
36 | |||
37 | /** |
||
38 | * @param string|int $event |
||
39 | * @param mixed $data |
||
40 | */ |
||
41 | public function fire($event, $data = null) |
||
59 | |||
60 | /** |
||
61 | * @return int|string |
||
62 | */ |
||
63 | public function getCurrentState() |
||
67 | |||
68 | /** |
||
69 | * @param string|int $state |
||
70 | * |
||
71 | * @return bool |
||
72 | */ |
||
73 | public function isInState($state) |
||
79 | |||
80 | public function toDotGraph() |
||
117 | |||
118 | /** |
||
119 | * @param StateConfiguration $child |
||
120 | * @param StateConfiguration $parent |
||
121 | * |
||
122 | * @return bool |
||
123 | */ |
||
124 | private function isSubState(StateConfiguration $child, StateConfiguration $parent) |
||
142 | |||
143 | /** |
||
144 | * @param string|int $state |
||
145 | * |
||
146 | * @return StateConfiguration |
||
147 | */ |
||
148 | private function getState($state) |
||
156 | |||
157 | /** |
||
158 | * @param StateConfiguration $previousState |
||
159 | * @param string|int $event |
||
160 | * @param StateConfiguration $nextState |
||
161 | * @param mixed $data |
||
162 | */ |
||
163 | private function transition(StateConfiguration $previousState, $event, StateConfiguration $nextState, $data) |
||
175 | } |
||
176 |
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.