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 = []) |
||
229 | |||
230 | /** |
||
231 | * Get the current context of the scan. |
||
232 | * |
||
233 | * @param null|string $match To check whether the current status is this value |
||
234 | * |
||
235 | * @return string|bool |
||
236 | */ |
||
237 | protected function status($match = null) |
||
247 | |||
248 | /** |
||
249 | * Add a new status to the stack. |
||
250 | * |
||
251 | * @param string $status |
||
252 | */ |
||
253 | protected function downStatus($status) |
||
257 | |||
258 | /** |
||
259 | * Removes and return the current status. |
||
260 | * |
||
261 | * @return string|null |
||
262 | */ |
||
263 | protected function upStatus() |
||
267 | |||
268 | /** |
||
269 | * Prepares the arguments found in functions. |
||
270 | * |
||
271 | * @param string $argument |
||
272 | * |
||
273 | * @return string |
||
274 | */ |
||
275 | protected static function prepareArgument($argument) |
||
281 | |||
282 | /** |
||
283 | * Decodes a string with an argument. |
||
284 | * |
||
285 | * @param string $value |
||
286 | * |
||
287 | * @return string |
||
288 | */ |
||
289 | protected static function convertString($value) |
||
320 | } |
||
321 |
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVar
assignment in line 1 and the$higher
assignment in line 2 are dead. The first because$myVar
is never used and the second because$higher
is always overwritten for every possible time line.