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 |
||
| 10 | class BetweenRule extends AndRule |
||
| 11 | { |
||
| 12 | /** @var string operator */ |
||
| 13 | const operator = '><'; |
||
| 14 | |||
| 15 | /** |
||
| 16 | */ |
||
| 17 | 16 | public function __construct( $field, array $limits ) |
|
| 22 | |||
| 23 | /** |
||
| 24 | * @return mixed |
||
| 25 | */ |
||
| 26 | 22 | public function getMinimum() |
|
| 30 | |||
| 31 | /** |
||
| 32 | * @return mixed |
||
| 33 | */ |
||
| 34 | 22 | public function getMaximum() |
|
| 38 | |||
| 39 | /** |
||
| 40 | * @return array |
||
| 41 | */ |
||
| 42 | 14 | public function getValues() |
|
| 49 | |||
| 50 | /** |
||
| 51 | */ |
||
| 52 | 36 | public function getField() |
|
| 74 | |||
| 75 | /** |
||
| 76 | * Checks if the range is valid. |
||
| 77 | * |
||
| 78 | * @return bool |
||
| 79 | */ |
||
| 80 | 1 | public function hasSolution(array $contextual_options=[]) |
|
| 84 | |||
| 85 | /** |
||
| 86 | * @param array $options + show_instance=false Display the operator of the rule or its instance id |
||
| 87 | * |
||
| 88 | * @return array |
||
| 89 | */ |
||
| 90 | 35 | public function toArray(array $options=[]) |
|
| 109 | |||
| 110 | /** |
||
| 111 | */ |
||
| 112 | 1 | View Code Duplication | public function toString(array $options=[]) |
| 129 | |||
| 130 | /**/ |
||
| 131 | } |
||
| 132 |
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: