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 |
||
17 | View Code Duplication | class UserCreateAction |
|
|
|||
18 | { |
||
19 | /** |
||
20 | * @var ResponseFactory |
||
21 | */ |
||
22 | private $responseFactory; |
||
23 | |||
24 | /** |
||
25 | * @var UserManager |
||
26 | */ |
||
27 | private $userManager; |
||
28 | |||
29 | /** |
||
30 | * UserCreateAction constructor. |
||
31 | * |
||
32 | * @param ResponseFactory $responseFactory |
||
33 | * @param UserManager $userManager |
||
34 | */ |
||
35 | public function __construct(ResponseFactory $responseFactory, UserManager $userManager) |
||
40 | |||
41 | /** |
||
42 | * @apiVersion 1.0.0 |
||
43 | * @api {post} /v1/users Create |
||
44 | * @apiName Create |
||
45 | * @apiGroup Users |
||
46 | * @apiHeader {String} Accept application/json |
||
47 | * @apiHeader {String} Content-type application/json |
||
48 | * @apiParamExample {json} Request-Body-Example: |
||
49 | * { |
||
50 | * "name": "username", |
||
51 | * "email": "[email protected]", |
||
52 | * "password": "password" |
||
53 | * } |
||
54 | * @apiSuccessExample {json} Success-Response: |
||
55 | * HTTP/1.1 201 Created |
||
56 | * { |
||
57 | * "id": 1, |
||
58 | * "name": "username", |
||
59 | * "email": "[email protected]", |
||
60 | * "role": "Customer", |
||
61 | * "created_at": "2099-12-31T23:59:59+00:00", |
||
62 | * "updated_at": "2099-12-31T23:59:59+00:00" |
||
63 | * } |
||
64 | */ |
||
65 | |||
66 | /** |
||
67 | * Create a user. |
||
68 | * |
||
69 | * @param Request $request |
||
70 | * @return JsonResponse |
||
71 | */ |
||
72 | public function __invoke(Request $request): JsonResponse |
||
78 | } |
||
79 |
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.