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 |
||
12 | View Code Duplication | final class AdvancedErrorHandler implements ErrorHandlerInterface |
|
|
|||
13 | { |
||
14 | /** |
||
15 | * @var ContentTypeResolverInterface |
||
16 | */ |
||
17 | private $contentTypeResolver; |
||
18 | |||
19 | /** |
||
20 | * @var ErrorResponseProviderInterface |
||
21 | */ |
||
22 | private $fallbackProvider; |
||
23 | |||
24 | /** |
||
25 | * @var ErrorResponseProviderInterface[] |
||
26 | */ |
||
27 | private $providers = []; |
||
28 | |||
29 | /** |
||
30 | * @var LoggerInterface |
||
31 | */ |
||
32 | private $logger; |
||
33 | |||
34 | /** |
||
35 | * @param ContentTypeResolverInterface $contentTypeResolver |
||
36 | * @param ErrorResponseProviderInterface $fallbackProvider |
||
37 | * @param array $providers |
||
38 | * @param LoggerInterface|null $logger |
||
39 | */ |
||
40 | public function __construct( |
||
54 | |||
55 | /** |
||
56 | * @param ErrorResponseProviderInterface $provider |
||
57 | */ |
||
58 | private function addProvider(ErrorResponseProviderInterface $provider) |
||
62 | |||
63 | /** |
||
64 | * @param Request $request |
||
65 | * @param Response $response |
||
66 | * @param \Exception $exception |
||
67 | * |
||
68 | * @return Response |
||
69 | * |
||
70 | * @throws \LogicException |
||
71 | */ |
||
72 | public function __invoke(Request $request, Response $response, \Exception $exception): Response |
||
84 | |||
85 | /** |
||
86 | * @param \Exception $exception |
||
87 | */ |
||
88 | private function logException(\Exception $exception) |
||
104 | } |
||
105 |
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.