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 |
||
7 | class Runner |
||
8 | { |
||
9 | /** @var Config */ |
||
10 | protected $config; |
||
11 | |||
12 | /** @var CCA */ |
||
13 | protected $cca; |
||
14 | |||
15 | public function __construct(Config $config) |
||
21 | |||
22 | /** |
||
23 | * Run the CCA and return the $numIterations-th state. |
||
24 | * |
||
25 | * @param int $numIterations |
||
26 | * |
||
27 | * @return State |
||
28 | */ |
||
29 | View Code Duplication | public function getLastState(int $numIterations): State |
|
|
|||
30 | { |
||
31 | do { |
||
32 | $state = $this->cca->getState(); |
||
33 | |||
34 | $iteration = $this->cca->cycle(); |
||
35 | } while ($iteration < $numIterations); |
||
36 | |||
37 | return $state; |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * Run the CCA and return an array with first $numIterations states. |
||
42 | * |
||
43 | * @param int $numIterations |
||
44 | * |
||
45 | * @return State[] |
||
46 | */ |
||
47 | View Code Duplication | public function getFirstStates(int $numIterations): array |
|
48 | { |
||
49 | $states = []; |
||
50 | |||
51 | do { |
||
52 | $states[] = $this->cca->getState(); |
||
53 | |||
54 | $iteration = $this->cca->cycle(); |
||
55 | } while ($iteration < $numIterations); |
||
56 | |||
57 | return $states; |
||
58 | } |
||
59 | |||
60 | /** |
||
61 | * Run the CCA and return the first looping states it encounters. If no loop is found within $maxIterations, |
||
62 | * a LoopNotFoundException exception will be thrown. |
||
63 | * |
||
64 | * @param int $maxIterations |
||
65 | * |
||
66 | * @throws LoopNotFoundException |
||
67 | * |
||
68 | * @return State[] |
||
69 | */ |
||
70 | public function getFirstLoop(int $maxIterations) |
||
98 | } |
||
99 |
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.