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 JsFunctionsScanner 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 JsFunctionsScanner, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 5 | class JsFunctionsScanner extends FunctionsScanner |
||
| 6 | { |
||
| 7 | protected $code; |
||
| 8 | protected $status = []; |
||
| 9 | |||
| 10 | /** |
||
| 11 | * Constructor. |
||
| 12 | * |
||
| 13 | * @param string $code The php code to scan |
||
| 14 | */ |
||
| 15 | public function __construct($code) |
||
| 19 | |||
| 20 | /** |
||
| 21 | * {@inheritdoc} |
||
| 22 | */ |
||
| 23 | public function getFunctions(array $constants = []) |
||
| 185 | |||
| 186 | /** |
||
| 187 | * Get the current context of the scan. |
||
| 188 | * |
||
| 189 | * @param null|string $match To check whether the current status is this value |
||
| 190 | * |
||
| 191 | * @return string|bool |
||
| 192 | */ |
||
| 193 | protected function status($match = null) |
||
| 203 | |||
| 204 | /** |
||
| 205 | * Add a new status to the stack. |
||
| 206 | * |
||
| 207 | * @param string $status |
||
| 208 | */ |
||
| 209 | protected function downStatus($status) |
||
| 213 | |||
| 214 | /** |
||
| 215 | * Removes and return the current status. |
||
| 216 | * |
||
| 217 | * @return string|null |
||
| 218 | */ |
||
| 219 | protected function upStatus() |
||
| 223 | |||
| 224 | /** |
||
| 225 | * Prepares the arguments found in functions. |
||
| 226 | * |
||
| 227 | * @param string $argument |
||
| 228 | * |
||
| 229 | * @return string |
||
| 230 | */ |
||
| 231 | protected static function prepareArgument($argument) |
||
| 237 | } |
||
| 238 |
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVarassignment in line 1 and the$higherassignment in line 2 are dead. The first because$myVaris never used and the second because$higheris always overwritten for every possible time line.