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 |
||
13 | class TaskManager |
||
14 | { |
||
15 | /** |
||
16 | * @var array|AbstractTask[] |
||
17 | */ |
||
18 | private $abortedTasks; |
||
19 | |||
20 | /** |
||
21 | * @var bool |
||
22 | */ |
||
23 | private $areThereOpenTasksLeft; |
||
24 | |||
25 | /** |
||
26 | * @var array|AbstractTask[] |
||
27 | */ |
||
28 | private $finishedTasks; |
||
29 | |||
30 | /** |
||
31 | * @var array|AbstractTask[] |
||
32 | */ |
||
33 | private $openTasks; |
||
34 | |||
35 | /** |
||
36 | * @var array|AbstractTask[] |
||
37 | */ |
||
38 | private $runningTasks; |
||
39 | |||
40 | public function __construct() |
||
48 | |||
49 | /** |
||
50 | * @return bool |
||
51 | */ |
||
52 | public function areThereOpenTasksLeft() |
||
56 | |||
57 | /** |
||
58 | * @param AbstractTask $task |
||
59 | * @return $this |
||
60 | */ |
||
61 | public function addOpenTask(AbstractTask $task) |
||
68 | |||
69 | /** |
||
70 | * @return null|AbstractTask |
||
71 | */ |
||
72 | public function getOpenTask() |
||
82 | |||
83 | /** |
||
84 | * @param AbstractTask $task |
||
85 | * @throws RuntimeException |
||
86 | */ |
||
87 | View Code Duplication | public function markRunningTaskAsAborted(AbstractTask $task) |
|
95 | |||
96 | /** |
||
97 | * @param AbstractTask $task |
||
98 | * @throws RuntimeException |
||
99 | */ |
||
100 | View Code Duplication | public function markRunningTaskAsFinished(AbstractTask $task) |
|
108 | |||
109 | /** |
||
110 | * @param AbstractTask $task |
||
111 | * @throws InvalidArgumentException |
||
112 | * @todo implement validation if task is not in open|finished|aborted|running array |
||
113 | */ |
||
114 | public function markOpenTaskAsRunning(AbstractTask $task) |
||
121 | |||
122 | /** |
||
123 | * @param AbstractTask $task |
||
124 | * @return string |
||
125 | * @throws RuntimeException |
||
126 | */ |
||
127 | private function getValidRunningTaskKey(AbstractTask $task) |
||
139 | |||
140 | /** |
||
141 | * @param AbstractTask $task |
||
142 | * @return string |
||
143 | */ |
||
144 | private function getArrayIndexKey(AbstractTask $task) |
||
148 | } |
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.