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 |
||
10 | class Products extends Endpoint implements GetContract, CreationContract |
||
11 | { |
||
12 | /** |
||
13 | * Get a page of products list. |
||
14 | * |
||
15 | * @param array $query the request query string. |
||
16 | * |
||
17 | * @return stdObject |
||
18 | */ |
||
19 | 3 | public function paginate(array $query = []) |
|
23 | |||
24 | /** |
||
25 | * Get a specific product. |
||
26 | * |
||
27 | * @param int $id the product id. |
||
28 | * |
||
29 | * @return stdObject |
||
30 | */ |
||
31 | 3 | public function get($id) |
|
35 | |||
36 | /** |
||
37 | * Create a new product. |
||
38 | * |
||
39 | * @return ProductData |
||
40 | */ |
||
41 | 3 | public function create() |
|
45 | |||
46 | /** |
||
47 | * Update a existing product. |
||
48 | * |
||
49 | * @return ProductData |
||
50 | */ |
||
51 | 3 | public function update($id) |
|
55 | |||
56 | /** |
||
57 | * Send the save request. |
||
58 | * |
||
59 | * @param PersonData $data |
||
60 | * |
||
61 | * @return stdClass |
||
62 | */ |
||
63 | 6 | View Code Duplication | public function save(ProductData $data) |
|
|||
64 | { |
||
65 | 6 | $id = $data->getId(); |
|
66 | |||
67 | 6 | return $this->run( |
|
68 | 6 | $id == null ? 'POST' : 'PUT', |
|
69 | 6 | 'operacional/produtos'.($id > 0 ? '/'.$id : null), |
|
70 | 6 | ['json' => $data->toArray()] |
|
71 | 6 | ); |
|
72 | } |
||
73 | |||
74 | /** |
||
75 | * Delete a product. |
||
76 | * |
||
77 | * @param int $id |
||
78 | * |
||
79 | * @return bool |
||
80 | */ |
||
81 | 3 | public function delete($id) |
|
85 | |||
86 | /** |
||
87 | * Get the product price table info. |
||
88 | * |
||
89 | * @return ProductPriceTable |
||
90 | */ |
||
91 | public function priceTableInfo() |
||
95 | } |
||
96 |
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.