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 ConditionParser 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 ConditionParser, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 9 | class ConditionParser { |
||
| 10 | private $firstPart; |
||
| 11 | private $condition; |
||
| 12 | private $parts=[]; |
||
| 13 | private $params; |
||
| 14 | private $invertedParams=true; |
||
| 15 | |||
| 16 | public function __construct($condition=null,$firstPart=null,$params=null){ |
||
| 23 | |||
| 24 | public function addKeyValues($keyValues,$classname,$separator=" AND ") { |
||
| 43 | |||
| 44 | private function addParams($value){ |
||
| 50 | |||
| 51 | public function addPart($condition,$value){ |
||
| 58 | |||
| 59 | public function addParts($condition,$values){ |
||
| 66 | |||
| 67 | public function compileParts($separator=" OR "){ |
||
| 80 | |||
| 81 | private function refactorParts(){ |
||
| 90 | |||
| 91 | private function parseKey($keyValues,$className){ |
||
| 100 | |||
| 101 | /** |
||
| 102 | * @return string |
||
| 103 | */ |
||
| 104 | public function getCondition() { |
||
| 113 | |||
| 114 | /** |
||
| 115 | * @return mixed |
||
| 116 | */ |
||
| 117 | public function getParams() { |
||
| 126 | |||
| 127 | /** |
||
| 128 | * @return mixed |
||
| 129 | */ |
||
| 130 | public function hasParam($value) { |
||
| 139 | |||
| 140 | public function countParts(){ |
||
| 145 | |||
| 146 | /** |
||
| 147 | * @param string $condition |
||
| 148 | */ |
||
| 149 | public function setCondition($condition) { |
||
| 153 | |||
| 154 | /** |
||
| 155 | * @param mixed $params |
||
| 156 | */ |
||
| 157 | public function setParams($params) { |
||
| 162 | |||
| 163 | public function limitOne(){ |
||
| 170 | |||
| 171 | public static function simple($condition,$params){ |
||
| 176 | |||
| 177 | } |
||
| 178 | |||
| 179 |
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.