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 | class PostController extends AbstractWidgetController |
||
13 | { |
||
14 | /** |
||
15 | * @var PostRepositoryInterface Posts |
||
16 | */ |
||
17 | protected $posts; |
||
18 | |||
19 | /** |
||
20 | * @var PaginatorBuilder Paginator builder |
||
21 | */ |
||
22 | protected $paginatorBuilder; |
||
23 | |||
24 | public function __construct( |
||
31 | |||
32 | /** |
||
33 | * / |
||
34 | * |
||
35 | * @param ServerRequestInterface $request |
||
36 | * |
||
37 | * @return string |
||
38 | */ |
||
39 | public function index(ServerRequestInterface $request) |
||
53 | |||
54 | /** |
||
55 | * /{slug} |
||
56 | * |
||
57 | * @param string $slug |
||
58 | * @return string |
||
59 | * @throws NotFoundException when post does not exist |
||
60 | */ |
||
61 | public function post($slug) |
||
73 | |||
74 | /** |
||
75 | * /kategoria/{slug} |
||
76 | * |
||
77 | * @param ServerRequestInterface $request |
||
78 | * @param string $slug |
||
79 | * @return string |
||
80 | */ |
||
81 | public function category(ServerRequestInterface $request, $slug) |
||
99 | |||
100 | /** |
||
101 | * /tag/{slug} |
||
102 | * |
||
103 | * @param ServerRequestInterface $request |
||
104 | * @param string $slug |
||
105 | * @return string |
||
106 | */ |
||
107 | View Code Duplication | public function tag(ServerRequestInterface $request, $slug) |
|
121 | |||
122 | /** |
||
123 | * /?q={term} |
||
124 | * |
||
125 | * @param ServerRequestInterface $request |
||
126 | * @param string $term |
||
127 | * @return string |
||
128 | */ |
||
129 | View Code Duplication | public function search(ServerRequestInterface $request, $term) |
|
144 | |||
145 | protected function notFound() |
||
151 | } |
||
152 |
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.