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 DiscussPostRepository |
||
11 | { |
||
12 | /** |
||
13 | * Create a new post instance after a valid validation. |
||
14 | * |
||
15 | * @param array $data The data used to create the post. |
||
16 | * |
||
17 | * @return \Xetaravel\Models\DiscussPost |
||
18 | */ |
||
19 | public static function create(array $data): DiscussPost |
||
49 | |||
50 | /** |
||
51 | * Find the previous post related to the given post. |
||
52 | * |
||
53 | * @param \Xetaravel\Models\DiscussPost $post |
||
54 | * |
||
55 | * @return \Xetaravel\Models\DiscussPost|null |
||
56 | */ |
||
57 | public static function findPreviousPost(DiscussPost $post) |
||
65 | } |
||
66 |
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: