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() |
||
174 | |||
175 | /** |
||
176 | * Get the current context of the scan. |
||
177 | * |
||
178 | * @param null|string $match To check whether the current status is this value |
||
179 | * |
||
180 | * @return string|bool |
||
181 | */ |
||
182 | protected function status($match = null) |
||
192 | |||
193 | /** |
||
194 | * Add a new status to the stack. |
||
195 | * |
||
196 | * @param string $status |
||
197 | */ |
||
198 | protected function downStatus($status) |
||
202 | |||
203 | /** |
||
204 | * Removes and return the current status. |
||
205 | * |
||
206 | * @return string|null |
||
207 | */ |
||
208 | protected function upStatus() |
||
212 | |||
213 | /** |
||
214 | * Prepares the arguments found in functions. |
||
215 | * |
||
216 | * @param string $argument |
||
217 | * |
||
218 | * @return string |
||
219 | */ |
||
220 | protected static function prepareArgument($argument) |
||
232 | } |
||
233 |
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.