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 |
||
18 | final class AsyncClient |
||
19 | { |
||
20 | /** |
||
21 | * @var Client |
||
22 | */ |
||
23 | protected $client; |
||
24 | |||
25 | /** |
||
26 | * @param LoopInterface $loop |
||
27 | * @param string $baseUrl |
||
28 | * @param string $username |
||
29 | * @param string $password |
||
30 | * @param Client|null $client |
||
31 | */ |
||
32 | public function __construct( |
||
45 | |||
46 | /** |
||
47 | * @return PromiseInterface |
||
48 | */ |
||
49 | public function overview(): PromiseInterface |
||
59 | |||
60 | /** |
||
61 | * @return ObservableInterface |
||
62 | */ |
||
63 | View Code Duplication | public function queues(): ObservableInterface |
|
75 | |||
76 | /** |
||
77 | * @return ObservableInterface |
||
78 | */ |
||
79 | View Code Duplication | public function connections(): ObservableInterface |
|
91 | } |
||
92 |
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: