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 |
||
11 | class TermQueryBuilder implements BuildsQueries |
||
12 | { |
||
13 | /** |
||
14 | * The term model |
||
15 | * @var Model |
||
16 | */ |
||
17 | protected $model; |
||
18 | |||
19 | /** |
||
20 | * Collection of arguments |
||
21 | * @var Collection |
||
22 | */ |
||
23 | protected $args; |
||
24 | |||
25 | /** |
||
26 | * Taxonomy Identifier |
||
27 | * @var string |
||
28 | */ |
||
29 | protected $taxonomy; |
||
30 | |||
31 | /** |
||
32 | * TermQueryBuilder Constructor. |
||
33 | * |
||
34 | * @param array $args |
||
35 | */ |
||
36 | public function __construct(array $args = []) |
||
40 | |||
41 | /** |
||
42 | * Restrict the query to terms of the provided Taxonomy. |
||
43 | * |
||
44 | * @param string $taxonomy |
||
45 | * |
||
46 | * @return $this |
||
47 | */ |
||
48 | public function forTaxonomy($taxonomy) |
||
54 | |||
55 | public function includeEmpty() |
||
61 | |||
62 | /** |
||
63 | * Limit the maximum number of results returned. |
||
64 | * |
||
65 | * @param int $max_results Maximum number to return. 0 or 'all' for unlimited. |
||
66 | * |
||
67 | * @return $this |
||
68 | */ |
||
69 | public function limit($max_results) |
||
75 | |||
76 | /** |
||
77 | * Get the query results. |
||
78 | * |
||
79 | * @throws WP_ErrorException |
||
80 | * |
||
81 | * @return Collection |
||
82 | */ |
||
83 | public function results() |
||
95 | |||
96 | /** |
||
97 | * Get the results as a collection of models. |
||
98 | * |
||
99 | * @return Collection |
||
100 | */ |
||
101 | View Code Duplication | protected function collectModels() |
|
113 | |||
114 | /** |
||
115 | * Set the model for this query. |
||
116 | * |
||
117 | * @param mixed $model |
||
118 | * |
||
119 | * @return $this |
||
120 | */ |
||
121 | public function setModel($model) |
||
127 | |||
128 | /** |
||
129 | * Get the model. |
||
130 | * |
||
131 | * @return mixed Model |
||
132 | */ |
||
133 | public function getModel() |
||
137 | |||
138 | /** |
||
139 | * Perform the term query and return the results. |
||
140 | * |
||
141 | * @throws WP_ErrorException |
||
142 | * |
||
143 | * @return array |
||
144 | */ |
||
145 | protected function fetchTerms() |
||
153 | } |
||
154 |
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.