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 |
||
8 | class Visibility |
||
9 | { |
||
10 | /** |
||
11 | * @return array |
||
12 | */ |
||
13 | 21 | public static function getMapping() |
|
21 | |||
22 | /** |
||
23 | * @param int $visibility |
||
24 | * @return int |
||
25 | */ |
||
26 | 21 | public static function get($visibility) |
|
31 | |||
32 | /** |
||
33 | * @param \PhpParser\Node\Stmt $context |
||
34 | * @return int |
||
35 | */ |
||
36 | 21 | public static function getForContext(Stmt $context) |
|
46 | |||
47 | /** |
||
48 | * @param string $visibility |
||
49 | * @return int |
||
50 | */ |
||
51 | 21 | View Code Duplication | public static function getModifier($visibility) |
61 | |||
62 | /** |
||
63 | * @param int $visibility |
||
64 | * @return string |
||
65 | */ |
||
66 | View Code Duplication | public static function toString($visibility) |
|
76 | } |
||
77 |
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: