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 |
||
12 | View Code Duplication | class ConfiguredQuery |
|
|
|||
13 | { |
||
14 | /** |
||
15 | * @var QueryBuilder |
||
16 | */ |
||
17 | private $queryBuilder; |
||
18 | |||
19 | /** |
||
20 | * @var array|OrderingConfiguration[] associative, keys are strings for ordering fields |
||
21 | */ |
||
22 | private $orderingConfigurations; |
||
23 | |||
24 | /** |
||
25 | * @var bool |
||
26 | */ |
||
27 | private $totalCountNeeded; |
||
28 | |||
29 | /** |
||
30 | * @var int|null |
||
31 | */ |
||
32 | private $maximumOffset; |
||
33 | |||
34 | /** |
||
35 | * @var callable |
||
36 | */ |
||
37 | private $itemTransformer; |
||
38 | |||
39 | public function __construct(QueryBuilder $queryBuilder) |
||
45 | |||
46 | public function addOrderingConfiguration(string $orderBy, OrderingConfiguration $configuration): self |
||
56 | |||
57 | /** |
||
58 | * @param array|OrderingConfiguration[] $orderingConfigurations array of `orderBy => OrderingConfiguration` pairs |
||
59 | * @return ConfiguredQuery |
||
60 | */ |
||
61 | public function addOrderingConfigurations(array $orderingConfigurations): self |
||
69 | |||
70 | public function getOrderingConfigurationFor(string $orderBy): OrderingConfiguration |
||
78 | |||
79 | /** |
||
80 | * @return QueryBuilder |
||
81 | */ |
||
82 | public function getQueryBuilder(): QueryBuilder |
||
86 | |||
87 | /** |
||
88 | * @return bool |
||
89 | */ |
||
90 | public function isTotalCountNeeded(): bool |
||
94 | |||
95 | /** |
||
96 | * @param bool $totalCountNeeded |
||
97 | * @return $this |
||
98 | */ |
||
99 | public function setTotalCountNeeded(bool $totalCountNeeded): self |
||
104 | |||
105 | /** |
||
106 | * @param int $maximumOffset |
||
107 | * @return $this |
||
108 | */ |
||
109 | public function setMaximumOffset(int $maximumOffset): self |
||
114 | |||
115 | public function hasMaximumOffset(): bool |
||
119 | |||
120 | /** |
||
121 | * @return int |
||
122 | * @throws RuntimeException if maximum offset was not set. Check with hasMaximumOffset beforehand |
||
123 | */ |
||
124 | public function getMaximumOffset(): int |
||
132 | |||
133 | /** |
||
134 | * @return callable|null |
||
135 | */ |
||
136 | public function getItemTransformer() |
||
140 | |||
141 | public function setItemTransformer(callable $itemTransformer): self |
||
147 | } |
||
148 |
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.