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 |
||
| 16 | class SwitchLocaleController extends AbstractActionController implements ServiceLocatorAwareInterface |
||
| 17 | { |
||
| 18 | /** |
||
| 19 | * @var $localeService : Service des locales |
||
| 20 | */ |
||
| 21 | protected $localeService; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * switchAction : permet de switcher de langue en fonction d'un context (back/front) |
||
| 25 | * locale : locale pour switch |
||
| 26 | * context : (back/front) |
||
| 27 | * referer : retour à la page |
||
| 28 | * |
||
| 29 | * @return Redirect $redirect redirect to referer |
||
| 30 | */ |
||
| 31 | public function switchAction() |
||
| 42 | |||
| 43 | |||
| 44 | /** |
||
| 45 | * getServiceLocator : Recuperer le service locator |
||
| 46 | * @return ServiceLocator $serviceLocator |
||
| 47 | */ |
||
| 48 | public function getServiceLocator() |
||
| 52 | |||
| 53 | /** |
||
| 54 | * setServiceLocator : set le service locator |
||
| 55 | */ |
||
| 56 | public function setServiceLocator(ServiceLocatorInterface $serviceLocator) |
||
| 60 | |||
| 61 | /** |
||
| 62 | * getLocaleService : Recuperer le service des locales |
||
| 63 | * |
||
| 64 | * @return Service/Locale $localeService |
||
| 65 | */ |
||
| 66 | View Code Duplication | public function getLocaleService() |
|
| 73 | } |
||
| 74 |
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: