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 |
||
9 | class QueryBuilder |
||
10 | { |
||
11 | /** |
||
12 | * @var ObjectNode |
||
13 | */ |
||
14 | protected $rootNode; |
||
15 | |||
16 | /** |
||
17 | * @var AbstractNode |
||
18 | */ |
||
19 | protected $node; |
||
20 | |||
21 | 16 | public function __construct() |
|
26 | |||
27 | /** |
||
28 | * @param AbstractNode $node |
||
29 | * @param bool $allowDefault |
||
30 | * @return $this |
||
31 | * @throws \Exception |
||
32 | */ |
||
33 | 3 | View Code Duplication | public function addToArrayNode(AbstractNode $node, $allowDefault = false) |
|
|||
34 | { |
||
35 | 3 | if (!$this->node instanceof ArrayNode) { |
|
36 | 1 | throw new \Exception(sprintf('You cannot call %s on node type: %s', __FUNCTION__, get_class($this->node))); |
|
37 | } |
||
38 | |||
39 | 2 | $this->node->add($node, $allowDefault); |
|
40 | 2 | $this->reassignParent($node); |
|
41 | |||
42 | 2 | return $this; |
|
43 | } |
||
44 | |||
45 | /** |
||
46 | * @param string $key |
||
47 | * @param AbstractNode $node |
||
48 | * @param bool $allowDefault |
||
49 | * @return $this |
||
50 | * @throws \Exception |
||
51 | */ |
||
52 | 15 | View Code Duplication | public function addToObjectNode($key, AbstractNode $node, $allowDefault = false) |
53 | { |
||
54 | 15 | if (!$this->node instanceof ObjectNode) { |
|
55 | 1 | throw new \Exception(sprintf('You cannot call %s on node type: %s', __FUNCTION__, get_class($this->node))); |
|
56 | } |
||
57 | |||
58 | 15 | $this->node->add($key, $node, $allowDefault); |
|
59 | 15 | $this->reassignParent($node); |
|
60 | |||
61 | 15 | return $this; |
|
62 | } |
||
63 | |||
64 | /** |
||
65 | * @param AbstractNode $node |
||
66 | */ |
||
67 | 15 | protected function reassignParent(AbstractNode $node) |
|
73 | |||
74 | /** |
||
75 | * @return $this |
||
76 | */ |
||
77 | 1 | public function end() |
|
83 | |||
84 | /** |
||
85 | * @return Query |
||
86 | */ |
||
87 | 14 | public function query() |
|
91 | } |
||
92 |
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.