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 |
||
13 | class EncodingNegotiator |
||
14 | { |
||
15 | const KEY = 'ENCODING'; |
||
16 | |||
17 | /** |
||
18 | * @var array Available encodings |
||
19 | */ |
||
20 | private $encodings = [ |
||
21 | 'gzip', |
||
22 | 'deflate', |
||
23 | ]; |
||
24 | |||
25 | /** |
||
26 | * Returns the encoding. |
||
27 | * |
||
28 | * @param ServerRequestInterface $request |
||
29 | * |
||
30 | * @return string|null |
||
31 | */ |
||
32 | public static function getEncoding(ServerRequestInterface $request) |
||
36 | |||
37 | /** |
||
38 | * Constructor. Defines de available encodings. |
||
39 | * |
||
40 | * @param array $encodings |
||
41 | */ |
||
42 | public function __construct(array $encodings = null) |
||
48 | |||
49 | /** |
||
50 | * Configure the available encodings. |
||
51 | * |
||
52 | * @param array $encodings |
||
53 | * |
||
54 | * @return self |
||
55 | */ |
||
56 | public function encodings(array $encodings) |
||
62 | |||
63 | /** |
||
64 | * Execute the middleware. |
||
65 | * |
||
66 | * @param ServerRequestInterface $request |
||
67 | * @param ResponseInterface $response |
||
68 | * @param callable $next |
||
69 | * |
||
70 | * @return ResponseInterface |
||
71 | */ |
||
72 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
78 | |||
79 | /** |
||
80 | * Returns the encoding format using the Accept-Encoding header. |
||
81 | * |
||
82 | * @return null|string |
||
83 | */ |
||
84 | View Code Duplication | private function getFromHeader(ServerRequestInterface $request) |
|
98 | } |
||
99 |
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.