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 |
||
13 | class ExpressionVisitor |
||
14 | { |
||
15 | private $queryBuilder; |
||
16 | private $sourceAlias; |
||
17 | |||
18 | /** |
||
19 | * @param QueryBuilder $queryBuilder |
||
20 | */ |
||
21 | public function __construct(QueryBuilder $queryBuilder, string $sourceAlias) |
||
26 | |||
27 | /** |
||
28 | * Walk the given expression to build up the PHPCR-ODM query builder. |
||
29 | * |
||
30 | * @param Expression $expr |
||
31 | * @param AbstractNode|null $parentNode |
||
32 | */ |
||
33 | public function dispatch(Expression $expr, AbstractNode $parentNode = null) |
||
34 | { |
||
35 | if ($parentNode === null) { |
||
36 | $parentNode = $this->queryBuilder->where(); |
||
37 | } |
||
38 | |||
39 | View Code Duplication | switch (true) { |
|
|
|||
40 | case $expr instanceof Comparison: |
||
41 | return $this->walkComparison($expr, $parentNode); |
||
42 | |||
43 | case $expr instanceof Composite: |
||
44 | return $this->walkComposite($expr, $parentNode); |
||
45 | } |
||
46 | |||
47 | throw new \RuntimeException('Unknown Expression: ' . get_class($expr)); |
||
48 | } |
||
49 | |||
50 | /** |
||
51 | * {@inheritdoc} |
||
52 | */ |
||
53 | private function walkComparison(Comparison $comparison, AbstractNode $parentNode) |
||
101 | |||
102 | /** |
||
103 | * {@inheritdoc} |
||
104 | */ |
||
105 | private function walkComposite(Composite $expression, AbstractNode $parentNode) |
||
130 | |||
131 | /** |
||
132 | * @param string $field |
||
133 | * |
||
134 | * @return string |
||
135 | */ |
||
136 | private function getField($field): string |
||
140 | |||
141 | /** |
||
142 | * @param AbstractNode $parentNode |
||
143 | * @param string $field |
||
144 | * @param array $values |
||
145 | */ |
||
146 | private function getInConstraint(AbstractNode $parentNode, $field, array $values) |
||
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.