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 TransactionController extends Controller |
||
12 | { |
||
13 | /** |
||
14 | * @var TransactionService |
||
15 | */ |
||
16 | private $transactionService; |
||
17 | |||
18 | /** |
||
19 | * TransactionController constructor. |
||
20 | * |
||
21 | * @param TransactionService $transactionService |
||
22 | */ |
||
23 | public function __construct(TransactionService $transactionService) |
||
27 | |||
28 | /** |
||
29 | * Show the form for creating a new resource. |
||
30 | * |
||
31 | * @return \Illuminate\Http\Response |
||
32 | */ |
||
33 | public function create() |
||
37 | |||
38 | /** |
||
39 | * Store a newly created resource in storage. |
||
40 | * |
||
41 | * @param TransactionRequest|Request $request |
||
42 | * |
||
43 | * @return \Illuminate\Http\Response |
||
44 | */ |
||
45 | View Code Duplication | public function store(TransactionRequest $request) |
|
54 | |||
55 | /** |
||
56 | * Update the specified resource in storage. |
||
57 | * |
||
58 | * @param TransactionRequest|Request $request |
||
59 | * @param int $id |
||
60 | * |
||
61 | * @return \Illuminate\Http\Response |
||
62 | */ |
||
63 | View Code Duplication | public function update(TransactionRequest $request, $id) |
|
72 | |||
73 | /** |
||
74 | * Remove the specified resource from storage. |
||
75 | * |
||
76 | * @param int $id |
||
77 | * |
||
78 | * @return \Illuminate\Http\Response |
||
79 | */ |
||
80 | public function destroy($id) |
||
81 | { |
||
82 | abort_unless(Auth::user()->transactions()->whereId($id)->exists(), 403); |
||
83 | |||
84 | Transaction::destroy($id); |
||
85 | } |
||
86 | } |
||
87 |
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.