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 |
||
21 | final class CartController |
||
22 | { |
||
23 | /** |
||
24 | * @var CommandBusInterface |
||
25 | */ |
||
26 | private $commandBus; |
||
27 | |||
28 | /** |
||
29 | * @param CommandBusInterface $commandBus |
||
30 | */ |
||
31 | public function __construct(CommandBusInterface $commandBus) |
||
35 | |||
36 | /** |
||
37 | * @param Request $request |
||
38 | * |
||
39 | * @return Response |
||
40 | * |
||
41 | * @throws HttpException |
||
42 | */ |
||
43 | public function initializeAction(Request $request): Response |
||
51 | |||
52 | /** |
||
53 | * @param Request $request |
||
54 | * |
||
55 | * @return Response |
||
56 | * |
||
57 | * @throws HttpException |
||
58 | */ |
||
59 | public function addProductAction(Request $request): Response |
||
71 | |||
72 | /** |
||
73 | * @param Request $request |
||
74 | * |
||
75 | * @return Response |
||
76 | * |
||
77 | * @throws HttpException |
||
78 | */ |
||
79 | View Code Duplication | public function changeProductQuantityAction(Request $request): Response |
|
89 | |||
90 | /** |
||
91 | * @param Request $request |
||
92 | * |
||
93 | * @return Response |
||
94 | * |
||
95 | * @throws HttpException |
||
96 | */ |
||
97 | View Code Duplication | public function removeProductAction(Request $request): Response |
|
106 | |||
107 | /** |
||
108 | * @param Request $request |
||
109 | * |
||
110 | * @return Response |
||
111 | * |
||
112 | * @throws HttpException |
||
113 | */ |
||
114 | public function clearAction(Request $request): Response |
||
120 | |||
121 | /** |
||
122 | * @param $command |
||
123 | * |
||
124 | * @throws HttpException |
||
125 | */ |
||
126 | private function tryToHandleCommand($command) |
||
134 | } |
||
135 |
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.