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 |
||
5 | class NodeTraverser implements NodeTraverserInterface |
||
6 | { |
||
7 | /** |
||
8 | * @var NodeVisitor[] Visitors |
||
9 | */ |
||
10 | protected $visitors; |
||
11 | |||
12 | /** |
||
13 | * @var bool |
||
14 | */ |
||
15 | private $cloneNodes; |
||
16 | |||
17 | /** |
||
18 | * Constructs a node traverser. |
||
19 | * |
||
20 | * @param bool $cloneNodes Should the traverser clone the nodes when traversing the AST |
||
21 | */ |
||
22 | public function __construct($cloneNodes = false) { |
||
26 | |||
27 | /** |
||
28 | * Adds a visitor. |
||
29 | * |
||
30 | * @param NodeVisitor $visitor Visitor to add |
||
31 | */ |
||
32 | public function addVisitor(NodeVisitor $visitor) { |
||
35 | |||
36 | /** |
||
37 | * Removes an added visitor. |
||
38 | * |
||
39 | * @param NodeVisitor $visitor |
||
40 | */ |
||
41 | public function removeVisitor(NodeVisitor $visitor) { |
||
49 | |||
50 | /** |
||
51 | * Traverses an array of nodes using the registered visitors. |
||
52 | * |
||
53 | * @param Node[] $nodes Array of nodes |
||
54 | * |
||
55 | * @return Node[] Traversed array of nodes |
||
56 | */ |
||
57 | public function traverse(array $nodes) { |
||
74 | |||
75 | protected function traverseNode(Node $node) { |
||
110 | |||
111 | protected function traverseArray(array $nodes) { |
||
156 | } |
||
157 |
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.