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 | class SqlQuery |
||
8 | { |
||
9 | /** |
||
10 | * @var int |
||
11 | */ |
||
12 | private $number; |
||
13 | |||
14 | /** |
||
15 | * @var string |
||
16 | */ |
||
17 | private $sql; |
||
18 | |||
19 | /** |
||
20 | * @var array |
||
21 | */ |
||
22 | private $bindings; |
||
23 | |||
24 | /** |
||
25 | * @var int |
||
26 | */ |
||
27 | private $time; |
||
28 | |||
29 | /** |
||
30 | * SqlQuery constructor. |
||
31 | * |
||
32 | * @param int $number |
||
33 | * @param string $sql |
||
34 | * @param array $bindings |
||
35 | * @param int $time |
||
36 | */ |
||
37 | public function __construct($number, $sql, array $bindings, $time) |
||
44 | |||
45 | /** |
||
46 | * Get number of query. |
||
47 | * |
||
48 | * @return int |
||
49 | */ |
||
50 | public function number() |
||
54 | |||
55 | /** |
||
56 | * Get raw SQL (without bindings). |
||
57 | * |
||
58 | * @return string |
||
59 | */ |
||
60 | public function raw() |
||
64 | |||
65 | /** |
||
66 | * Get bindings. |
||
67 | * |
||
68 | * @return array |
||
69 | */ |
||
70 | public function bindings() |
||
74 | |||
75 | /** |
||
76 | * Get time. |
||
77 | * |
||
78 | * @return int |
||
79 | */ |
||
80 | public function time() |
||
84 | |||
85 | /** |
||
86 | * Get full query with values from bindings inserted. |
||
87 | * |
||
88 | * @return string |
||
89 | */ |
||
90 | public function get() |
||
95 | |||
96 | /** |
||
97 | * Format bindings values. |
||
98 | * |
||
99 | * @param array $bindings |
||
100 | * |
||
101 | * @return array |
||
102 | */ |
||
103 | protected function formatBindings($bindings) |
||
115 | } |
||
116 |
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.