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 Token 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 Token, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 23 | class Token |
||
| 24 | { |
||
| 25 | const NAME = null; |
||
| 26 | |||
| 27 | protected static $_id = 0; |
||
| 28 | |||
| 29 | public $pos; |
||
| 30 | public $name; |
||
| 31 | public $index = 1; |
||
| 32 | |||
| 33 | /** |
||
| 34 | * @var Token |
||
| 35 | */ |
||
| 36 | protected $_end; |
||
| 37 | |||
| 38 | /** |
||
| 39 | * @var Token |
||
| 40 | */ |
||
| 41 | protected $_start; |
||
| 42 | |||
| 43 | /** @var Rule */ |
||
| 44 | protected $_rule; |
||
| 45 | |||
| 46 | protected $_valid; |
||
| 47 | protected $_length; |
||
| 48 | |||
| 49 | public $id; |
||
| 50 | |||
| 51 | /** |
||
| 52 | * Token constructor. |
||
| 53 | */ |
||
| 54 | public function __construct(array $options) |
||
| 87 | |||
| 88 | public static function compare(Token $a, Token $b) |
||
| 110 | |||
| 111 | public function isStart() |
||
| 115 | |||
| 116 | public function isEnd() |
||
| 120 | |||
| 121 | public function isValid(Language $language, $context = null) |
||
| 129 | |||
| 130 | protected function validate(Language $language, $context) |
||
| 137 | |||
| 138 | public function setValid($valid = true) |
||
| 148 | |||
| 149 | /** |
||
| 150 | * @return mixed |
||
| 151 | */ |
||
| 152 | public function getStart() |
||
| 156 | |||
| 157 | /** |
||
| 158 | * @param Token $start |
||
| 159 | */ |
||
| 160 | View Code Duplication | public function setStart(Token $start = null) |
|
| 169 | |||
| 170 | /** |
||
| 171 | * @return Token|null |
||
| 172 | */ |
||
| 173 | public function getEnd() |
||
| 177 | |||
| 178 | /** |
||
| 179 | * @param Token $end |
||
| 180 | */ |
||
| 181 | View Code Duplication | public function setEnd(Token $end = null) |
|
| 191 | |||
| 192 | /** |
||
| 193 | * @return Rule |
||
| 194 | */ |
||
| 195 | public function getRule() |
||
| 199 | |||
| 200 | /** |
||
| 201 | * @param Rule $rule |
||
| 202 | */ |
||
| 203 | public function setRule(Rule $rule) |
||
| 207 | |||
| 208 | public function getLength() |
||
| 216 | |||
| 217 | public function dump($text = null) |
||
| 233 | } |