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 ProductsController extends Controller |
||
12 | { |
||
13 | /** |
||
14 | * ProductsController constructor. |
||
15 | */ |
||
16 | public function __construct() |
||
21 | |||
22 | View Code Duplication | public function index() |
|
|
|||
23 | { |
||
24 | $data['products'] = Products::with('category')->paginate(10); |
||
25 | $data['category'] = ProductsCategories::with('products')->paginate(10)->sortBy("name")->all(); |
||
26 | |||
27 | return view('products.index', $data); |
||
28 | } |
||
29 | |||
30 | public function categories() |
||
35 | |||
36 | public function edit_categories($id) |
||
41 | |||
42 | public function remove_category($id) |
||
50 | |||
51 | |||
52 | /** |
||
53 | * [METHOD]: Add a new product in the database. |
||
54 | * |
||
55 | * @url:platform POST: /products/save |
||
56 | * @see:phpunit TODO: write phpunit test in a later version. |
||
57 | * |
||
58 | * @param Requests\ProductValidator $input |
||
59 | * @return \Illuminate\Http\RedirectResponse |
||
60 | */ |
||
61 | public function store(Requests\ProductValidator $input) |
||
77 | |||
78 | /** |
||
79 | * [METHOD]: Add a new product category in the database. |
||
80 | * |
||
81 | * @url:platform POST: /products/categories/save |
||
82 | * |
||
83 | * @param Requests\ProductValidator $input |
||
84 | * @return \Illuminate\Http\RedirectResponse |
||
85 | */ |
||
86 | public function saveCat(Request $input) |
||
99 | |||
100 | |||
101 | public function remove($id) |
||
109 | } |
||
110 |
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.