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 |
||
22 | class RestController extends Controller |
||
23 | { |
||
24 | |||
25 | const MIME_TYPE_JSON = 'application/json'; |
||
26 | |||
27 | 39 | public function respond(AbstractApiResponse $apiResponse): Response |
|
36 | |||
37 | /** |
||
38 | * Process form |
||
39 | * @param Request $request |
||
40 | * @param FormInterface $form |
||
41 | */ |
||
42 | 13 | protected function processForm(Request $request, FormInterface $form) |
|
49 | |||
50 | /** {@inheritDoc} */ |
||
51 | 10 | protected function createFormBuilder($data = null, array $options = []): FormBuilder |
|
57 | |||
58 | /** |
||
59 | * Create collection api response with total, limit and offset parameters |
||
60 | * @param integer|null $limit |
||
61 | * @param integer|null $offset |
||
62 | */ |
||
63 | 4 | protected function createCompleteCollectionResponse(AbstractRepository $repository, $limit, $offset): CollectionApiResponse |
|
75 | |||
76 | /** |
||
77 | * @param string $entityFullName Entity class name |
||
78 | * @param string|int $id Entity id |
||
79 | * @return ApiError |
||
80 | * @throws EntityNotFoundException |
||
81 | */ |
||
82 | 5 | protected function createEntityNotFoundResponse(string $entityFullName, $id): ApiError |
|
86 | |||
87 | /** |
||
88 | * @param string|int $id |
||
89 | */ |
||
90 | 13 | View Code Duplication | protected function viewEntity(AbstractRepository $repository, $id): Response |
103 | |||
104 | 39 | private function setLocation(Response $response, AbstractApiResponse $apiResponse) |
|
110 | |||
111 | 39 | private function setContentType(AbstractApiResponse $apiResponse, Response $response) |
|
117 | } |
||
118 |
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.