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:
Complex classes like IPMI often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use IPMI, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 26 | class IPMI extends Sensors |
||
|
|
|||
| 27 | { |
||
| 28 | /** |
||
| 29 | * content to parse |
||
| 30 | * |
||
| 31 | * @var array |
||
| 32 | */ |
||
| 33 | private $_lines = array(); |
||
| 34 | |||
| 35 | /** |
||
| 36 | * fill the private content var through command or data access |
||
| 37 | */ |
||
| 38 | View Code Duplication | public function __construct() |
|
| 56 | |||
| 57 | /** |
||
| 58 | * get temperature information |
||
| 59 | * |
||
| 60 | * @return void |
||
| 61 | */ |
||
| 62 | View Code Duplication | private function _temperature() |
|
| 80 | |||
| 81 | /** |
||
| 82 | * get voltage information |
||
| 83 | * |
||
| 84 | * @return void |
||
| 85 | */ |
||
| 86 | private function _voltage() |
||
| 105 | |||
| 106 | /** |
||
| 107 | * get fan information |
||
| 108 | * |
||
| 109 | * @return void |
||
| 110 | */ |
||
| 111 | private function _fans() |
||
| 133 | |||
| 134 | /** |
||
| 135 | * get power information |
||
| 136 | * |
||
| 137 | * @return void |
||
| 138 | */ |
||
| 139 | View Code Duplication | private function _power() |
|
| 157 | |||
| 158 | /** |
||
| 159 | * get current information |
||
| 160 | * |
||
| 161 | * @return void |
||
| 162 | */ |
||
| 163 | View Code Duplication | private function _current() |
|
| 181 | |||
| 182 | /** |
||
| 183 | * get the information |
||
| 184 | * |
||
| 185 | * @see PSI_Interface_Sensor::build() |
||
| 186 | * |
||
| 187 | * @return Void |
||
| 188 | */ |
||
| 189 | public function build() |
||
| 197 | } |
||
| 198 |
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.