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 |
||
24 | class PageSeoController extends Controller |
||
25 | { |
||
26 | use VictoireAlertifyControllerTrait; |
||
27 | |||
28 | /** |
||
29 | * Display a form to edit Seo settings. |
||
30 | * |
||
31 | * @param Request $request |
||
32 | * @param View $view |
||
33 | * |
||
34 | * @Route("/{id}/settings", name="victoire_seo_pageSeo_settings") |
||
35 | * @Method("GET") |
||
36 | * @Template() |
||
37 | * |
||
38 | * @return JsonResponse |
||
39 | */ |
||
40 | public function settingsAction(Request $request, View $view) |
||
55 | |||
56 | /** |
||
57 | * Save Seo settings. |
||
58 | * |
||
59 | * @param Request $request |
||
60 | * @param View $view |
||
61 | * |
||
62 | * @Route("/{id}/settings", name="victoire_seo_pageSeo_settings_post") |
||
63 | * @Method("POST") |
||
64 | * @Template() |
||
65 | * |
||
66 | * @return JsonResponse |
||
67 | */ |
||
68 | public function settingsPostAction(Request $request, View $view) |
||
97 | |||
98 | /** |
||
99 | * Create PageSeo Form. |
||
100 | * |
||
101 | * @param PageSeo $pageSeo |
||
102 | * @param View $view |
||
103 | * |
||
104 | * @return FormInterface |
||
105 | */ |
||
106 | private function createSettingsForm(PageSeo $pageSeo, View $view) |
||
119 | |||
120 | /** |
||
121 | * Get JsonResponse array for Settings novalidate and form display. |
||
122 | * |
||
123 | * @param FormInterface $form |
||
124 | * @param View $view |
||
125 | * @param $novalidate |
||
126 | * |
||
127 | * @return array |
||
128 | */ |
||
129 | private function getNotPersistedSettingsResponse(FormInterface $form, View $view, $novalidate) |
||
149 | |||
150 | /** |
||
151 | * Get url for a View using ViewReferences if necessary. |
||
152 | * |
||
153 | * @param View $view |
||
154 | * |
||
155 | * @return string |
||
156 | */ |
||
157 | private function getViewUrl(View $view) |
||
171 | |||
172 | /** |
||
173 | * Return BusinessEntity seaoable properties if View is a BusinessTemplate. |
||
174 | * |
||
175 | * @param View $view |
||
176 | * |
||
177 | * @return array |
||
178 | */ |
||
179 | View Code Duplication | private function getBusinessProperties(View $view) |
|
191 | |||
192 | /** |
||
193 | * @return string |
||
194 | */ |
||
195 | private function getBaseTemplatePath() |
||
199 | } |
||
200 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: