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 UserController extends Controller |
||
23 | { |
||
24 | /** |
||
25 | * User overview page. |
||
26 | * |
||
27 | * @return Response A Response instance |
||
28 | */ |
||
29 | public function overviewAction() |
||
41 | |||
42 | /** |
||
43 | * Add user. |
||
44 | * |
||
45 | * @param Request $request A Request instance |
||
46 | * |
||
47 | * @return Response A Response instance |
||
48 | */ |
||
49 | View Code Duplication | public function addAction(Request $request) |
|
74 | |||
75 | /** |
||
76 | * @ParamConverter("user", class="AppBundle:User", options={"id" = "userId"}) |
||
77 | * |
||
78 | * Edit user |
||
79 | * |
||
80 | * @param Request $request A Request instance |
||
81 | * @param User $user |
||
82 | * |
||
83 | * @return Response A Response instance |
||
84 | */ |
||
85 | View Code Duplication | public function editAction(Request $request, User $user) |
|
86 | { |
||
87 | $userForm = $this->createForm(UserFormType::class, $user); |
||
88 | |||
89 | if ($request->isMethod('POST')) { |
||
90 | $userForm->handleRequest($request); |
||
91 | if ($userForm->isValid()) { |
||
92 | $userRepository = $this->get('packy.repository.user'); |
||
93 | $userRepository->update($user); |
||
94 | |||
95 | return $this->redirect($this->generateUrl('packy_user_overview')); |
||
96 | } |
||
97 | } |
||
98 | |||
99 | return $this->render( |
||
100 | 'AppBundle:User:form.html.twig', |
||
101 | [ |
||
102 | 'user' => $user, |
||
103 | 'userForm' => $userForm->createView(), |
||
104 | ] |
||
105 | ); |
||
106 | } |
||
107 | |||
108 | /** |
||
109 | * @ParamConverter("user", class="AppBundle:User", options={"id" = "userId"}) |
||
110 | * |
||
111 | * Delete user |
||
112 | * |
||
113 | * @param User $user |
||
114 | * |
||
115 | * @return RedirectResponse A Response instance |
||
116 | */ |
||
117 | public function deleteAction(User $user) |
||
118 | { |
||
119 | $userRepository = $this->get('packy.repository.user'); |
||
120 | $userRepository->delete($user); |
||
121 | |||
122 | return $this->redirect($this->generateUrl('packy_user_overview')); |
||
123 | } |
||
124 | } |
||
125 |
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.