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 |
||
| 20 | class ArgumentValidator extends BaseDefinitionValidator |
||
| 21 | { |
||
| 22 | /** |
||
| 23 | * @param Definition $definition |
||
| 24 | * @return bool |
||
| 25 | */ |
||
| 26 | 6551 | public function match(Definition $definition): bool |
|
| 30 | |||
| 31 | /** |
||
| 32 | * @param Definition|ArgumentDefinition $type |
||
| 33 | * @return void |
||
| 34 | * @throws \Railt\SDL\Exceptions\TypeConflictException |
||
| 35 | */ |
||
| 36 | 5545 | public function validate(Definition $type): void |
|
| 49 | |||
| 50 | /** |
||
| 51 | * @param ArgumentDefinition $type |
||
| 52 | * @param Inputable $definition |
||
| 53 | * @return void |
||
| 54 | * @throws TypeConflictException |
||
| 55 | */ |
||
| 56 | 5537 | private function validateDefaultValue(ArgumentDefinition $type, Inputable $definition): void |
|
| 76 | |||
| 77 | /** |
||
| 78 | * @param ArgumentDefinition $type |
||
| 79 | * @return void |
||
| 80 | * @throws TypeConflictException |
||
| 81 | */ |
||
| 82 | 5513 | private function validateNullDefaultValue(ArgumentDefinition $type): void |
|
| 90 | |||
| 91 | /** |
||
| 92 | * @param ArgumentDefinition $type |
||
| 93 | * @param array $defaults |
||
| 94 | * @return void |
||
| 95 | * @throws TypeConflictException |
||
| 96 | */ |
||
| 97 | 3036 | private function validateArrayDefaultValue(ArgumentDefinition $type, array $defaults): void |
|
| 119 | |||
| 120 | /** |
||
| 121 | * @param ArgumentDefinition $type |
||
| 122 | * @param Inputable $definition |
||
| 123 | * @param array $values |
||
| 124 | * @return void |
||
| 125 | * @throws TypeConflictException |
||
| 126 | */ |
||
| 127 | 1534 | private function validateDefaultListType(ArgumentDefinition $type, Inputable $definition, array $values): void |
|
| 145 | |||
| 146 | /** |
||
| 147 | * @param ArgumentDefinition $type |
||
| 148 | * @param Inputable $definition |
||
| 149 | * @param $value |
||
| 150 | * @return void |
||
| 151 | * @throws TypeConflictException |
||
| 152 | */ |
||
| 153 | 5310 | private function validateDefaultType(ArgumentDefinition $type, Inputable $definition, $value): void |
|
| 160 | } |
||
| 161 |
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: