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 FreeIPMI 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 FreeIPMI, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 26 | class FreeIPMI 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() |
|
| 76 | |||
| 77 | /** |
||
| 78 | * get voltage information |
||
| 79 | * |
||
| 80 | * @return void |
||
| 81 | */ |
||
| 82 | private function _voltage() |
||
| 97 | |||
| 98 | /** |
||
| 99 | * get fan information |
||
| 100 | * |
||
| 101 | * @return void |
||
| 102 | */ |
||
| 103 | private function _fans() |
||
| 121 | |||
| 122 | /** |
||
| 123 | * get power information |
||
| 124 | * |
||
| 125 | * @return void |
||
| 126 | */ |
||
| 127 | View Code Duplication | private function _power() |
|
| 141 | |||
| 142 | /** |
||
| 143 | * get current information |
||
| 144 | * |
||
| 145 | * @return void |
||
| 146 | */ |
||
| 147 | View Code Duplication | private function _current() |
|
| 161 | |||
| 162 | /** |
||
| 163 | * get the information |
||
| 164 | * |
||
| 165 | * @see PSI_Interface_Sensor::build() |
||
| 166 | * |
||
| 167 | * @return Void |
||
| 168 | */ |
||
| 169 | public function build() |
||
| 177 | } |
||
| 178 |
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.