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) |
||
| 20 | |||
| 21 | /** |
||
| 22 | * {@inheritdoc} |
||
| 23 | */ |
||
| 24 | public function getFunctions(array $constants = []) |
||
| 197 | |||
| 198 | /** |
||
| 199 | * Get the current context of the scan. |
||
| 200 | * |
||
| 201 | * @param null|string $match To check whether the current status is this value |
||
| 202 | * |
||
| 203 | * @return string|bool |
||
| 204 | */ |
||
| 205 | protected function status($match = null) |
||
| 215 | |||
| 216 | /** |
||
| 217 | * Add a new status to the stack. |
||
| 218 | * |
||
| 219 | * @param string $status |
||
| 220 | */ |
||
| 221 | protected function downStatus($status) |
||
| 225 | |||
| 226 | /** |
||
| 227 | * Removes and return the current status. |
||
| 228 | * |
||
| 229 | * @return string|null |
||
| 230 | */ |
||
| 231 | protected function upStatus() |
||
| 235 | |||
| 236 | /** |
||
| 237 | * Prepares the arguments found in functions. |
||
| 238 | * |
||
| 239 | * @param string $argument |
||
| 240 | * |
||
| 241 | * @return string |
||
| 242 | */ |
||
| 243 | protected static function prepareArgument($argument) |
||
| 262 | } |
||
| 263 |
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.