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 Modules\Translation\Repositories\Cache; |
||
| 7 | class CacheTranslationDecorator extends BaseCacheDecorator implements TranslationRepository |
||
| 8 | { |
||
| 9 | public function __construct(TranslationRepository $recipe) |
||
| 15 | |||
| 16 | /** |
||
| 17 | * @param string $key |
||
| 18 | * @param string $locale |
||
| 19 | * @return string |
||
| 20 | */ |
||
| 21 | public function findByKeyAndLocale($key, $locale = null) |
||
| 31 | |||
| 32 | View Code Duplication | public function allFormatted() |
|
| 42 | |||
| 43 | public function saveTranslationForLocaleAndKey($locale, $key, $value) |
||
| 49 | |||
| 50 | View Code Duplication | public function findTranslationByKey($key) |
|
| 60 | |||
| 61 | /** |
||
| 62 | * Update the given translation key with the given data |
||
| 63 | * @param string $key |
||
| 64 | * @param array $data |
||
| 65 | * @return mixed |
||
| 66 | */ |
||
| 67 | public function updateFromImport($key, array $data) |
||
| 73 | |||
| 74 | /** |
||
| 75 | * Set the given value on the given TranslationTranslation |
||
| 76 | * @param TranslationTranslation $translationTranslation |
||
| 77 | * @param string $value |
||
| 78 | * @return void |
||
| 79 | */ |
||
| 80 | public function updateTranslationToValue(TranslationTranslation $translationTranslation, $value) |
||
| 86 | } |
||
| 87 |
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: