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:
1 | <?php |
||
7 | class Prune |
||
8 | { |
||
9 | /** |
||
10 | * Prune a node collection by a callback so only the filtered nodes are left as children. |
||
11 | * Pruning a collection only keeps the filtered nodes and collapses the ancestor tree. |
||
12 | * Shaking a collection retains the ancestors for each filtered node |
||
13 | * |
||
14 | * @param Node $node |
||
15 | * @param callable $callback |
||
16 | * @return Node |
||
17 | * @internal param Node[] $nodes |
||
18 | */ |
||
19 | 12 | View Code Duplication | public function __invoke(Node $node, Callable $callback): Node |
28 | |||
29 | /** |
||
30 | * Blacklist of disallowed nodes |
||
31 | * Note: the passed callback determines the nodes which should be kept but here |
||
32 | * we reverse the callback so we get the nodes that need to be excluded |
||
33 | * |
||
34 | * @param $copiedNode |
||
35 | * @param callable $callback |
||
36 | * @return array |
||
37 | */ |
||
38 | 12 | private function getBlacklistedNodes(Node $copiedNode, Callable $callback): array |
|
47 | } |
||
48 |
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.