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 |
||
7 | abstract class Treeview extends Collection { |
||
8 | |||
9 | # Get join statement |
||
10 | |||
11 | protected function getQueryJoin(int $parent_id) { |
||
19 | |||
20 | # Get select query |
||
21 | |||
22 | private function getSelectQuery(int $parent_id, array $config, array $order_by) { |
||
34 | |||
35 | # Get count query |
||
36 | |||
37 | private function getCountQuery(int $parent_id) { |
||
43 | |||
44 | # Get depth query |
||
45 | |||
46 | private function getDepthQuery(int $parent_id) { |
||
56 | |||
57 | # Get subtree |
||
58 | |||
59 | public function subtree(int $parent_id = 0, array $config = [], array $order_by = []) { |
||
60 | |||
61 | if (!(static::$nesting && ($parent_id >= 0))) return false; |
||
62 | |||
63 | # Select entities |
||
64 | |||
65 | $query = $this->getSelectQuery($parent_id, $config, $order_by); |
||
66 | |||
67 | if (!(DB::send($query) && DB::last()->status)) return false; |
||
68 | |||
69 | # Process results |
||
70 | |||
71 | $items = [$parent_id => ['children' => []]]; |
||
72 | |||
73 | while (null !== ($data = DB::last()->row())) { |
||
74 | |||
75 | $dataset = Entitizer::dataset(static::$table, $data); |
||
76 | |||
77 | $items[$dataset->id] = ['dataset' => $dataset, 'children' => []]; |
||
78 | |||
79 | $items[intval($data['parent_id'])]['children'][] = $dataset->id; |
||
80 | } |
||
81 | |||
82 | # ------------------------ |
||
83 | |||
84 | return $items; |
||
85 | } |
||
86 | |||
87 | # Get subtree count |
||
88 | |||
89 | View Code Duplication | public function subtreeCount(int $parent_id = 0) { |
|
103 | |||
104 | # Get subtree depth |
||
105 | |||
106 | View Code Duplication | public function subtreeDepth(int $parent_id = 0) { |
|
120 | |||
121 | # Get path |
||
122 | |||
123 | public function path(int $parent_id = 0) { |
||
149 | } |
||
150 | } |
||
151 |
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.