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 namespace Distilleries\Expendable\Http\Controllers\Backend; |
||
| 11 | class UserController extends BaseComponent { |
||
| 12 | |||
| 13 | |||
| 14 | public function __construct(UserDatatable $datatable, UserForm $form, User $model, LayoutManagerContract $layoutManager) |
||
| 20 | |||
| 21 | // ------------------------------------------------------------------------------------------------ |
||
| 22 | // ------------------------------------------------------------------------------------------------ |
||
| 23 | // ------------------------------------------------------------------------------------------------ |
||
| 24 | |||
| 25 | |||
| 26 | public function getProfile(Guard $auth) |
||
| 30 | |||
| 31 | // ------------------------------------------------------------------------------------------------ |
||
| 32 | |||
| 33 | public function postProfile(Request $request, Guard $auth) |
||
| 44 | |||
| 45 | // ------------------------------------------------------------------------------------------------ |
||
| 46 | |||
| 47 | public function postSearchWithRole(Request $request) |
||
| 54 | |||
| 55 | |||
| 56 | View Code Duplication | public function postUnLock(Request $request){ |
|
| 64 | |||
| 65 | |||
| 66 | View Code Duplication | public function postLock(Request $request){ |
|
| 74 | |||
| 75 | } |
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 implementation 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 interface: