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 | class ProcessesGauge implements GaugeInterface |
||
16 | { |
||
17 | protected $cpuAbove; |
||
18 | |||
19 | protected $memoryAbove; |
||
20 | |||
21 | /** |
||
22 | * @var TopCommand |
||
23 | */ |
||
24 | protected $command; |
||
25 | |||
26 | /** |
||
27 | * ProcessesGauge constructor. |
||
28 | * |
||
29 | * Track CPU and memory of processes |
||
30 | * |
||
31 | * @param float $cpuAbove |
||
32 | * @param float $memoryAbove |
||
33 | */ |
||
34 | 1 | public function __construct($cpuAbove = 5.0, $memoryAbove = 1.0) |
|
41 | |||
42 | /** |
||
43 | * {@inheritdoc} |
||
44 | */ |
||
45 | public function getSamplingPeriod() |
||
49 | |||
50 | /** |
||
51 | * {@inheritdoc} |
||
52 | */ |
||
53 | 1 | public function getCollection() |
|
75 | |||
76 | /** |
||
77 | * Return parsed data for processes |
||
78 | */ |
||
79 | 1 | protected function getProcesses() |
|
88 | |||
89 | /** |
||
90 | * Return only those processes above certail value |
||
91 | * |
||
92 | * @param $processes Process[] |
||
93 | * @return array |
||
94 | */ |
||
95 | protected function filterAbove($processes, $gate) |
||
101 | |||
102 | /** |
||
103 | * Aggregate CPU for processes with the same name |
||
104 | * |
||
105 | * @param $processes Process[] |
||
106 | */ |
||
107 | 1 | View Code Duplication | protected function aggregateCpu($processes) |
122 | |||
123 | /** |
||
124 | * Aggregate memory for processes with the same name |
||
125 | * |
||
126 | * @param $processes Process[] |
||
127 | * @return array |
||
128 | */ |
||
129 | 1 | View Code Duplication | protected function aggregateMemory($processes) |
144 | |||
145 | /** |
||
146 | * Return command object for top utility |
||
147 | * |
||
148 | * @return TopCommand |
||
149 | */ |
||
150 | protected function getCommand() |
||
154 | |||
155 | } |
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.