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 InstanceViewer 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 InstanceViewer, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
5 | class InstanceViewer { |
||
6 | private $instance; |
||
7 | private $reflect; |
||
8 | private $properties; |
||
9 | private $captions; |
||
10 | private $visibleProperties; |
||
11 | private $values; |
||
12 | private static $index=0; |
||
13 | |||
14 | public function __construct($instance=NULL,$captions=NULL){ |
||
20 | |||
21 | public function getCaption($index){ |
||
24 | |||
25 | public function getCaptions(){ |
||
41 | |||
42 | View Code Duplication | public function getValues(){ |
|
51 | |||
52 | public function getCkValue(){ |
||
59 | |||
60 | public function getValue($index){ |
||
64 | |||
65 | private function _getValue($property,$index){ |
||
83 | |||
84 | public function insertField($index,$field){ |
||
88 | |||
89 | public function insertInField($index,$field){ |
||
102 | |||
103 | public function addField($field){ |
||
107 | |||
108 | public function count(){ |
||
111 | |||
112 | private function showableProperty(\ReflectionProperty $rProperty){ |
||
115 | |||
116 | public function setInstance($instance) { |
||
149 | |||
150 | private function getDefaultProperties(){ |
||
161 | |||
162 | public function setCaptions($captions) { |
||
166 | |||
167 | public function setVisibleProperties($visibleProperties) { |
||
171 | |||
172 | public function setValueFunction($index,$callback){ |
||
176 | |||
177 | public function setCkValueFunction($callback){ |
||
181 | |||
182 | public static function setIndex($index) { |
||
185 | |||
186 | public function getProperties() { |
||
189 | |||
190 | |||
191 | |||
192 | |||
193 | } |
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.