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 |
||
15 | class Interaction extends Model |
||
16 | { |
||
17 | use CanFilterByUser; |
||
18 | |||
19 | protected $casts = [ |
||
20 | 'liked' => 'boolean', |
||
21 | 'play_count' => 'integer', |
||
22 | ]; |
||
23 | |||
24 | protected $guarded = ['id']; |
||
25 | |||
26 | protected $hidden = ['id', 'user_id', 'created_at', 'updated_at']; |
||
27 | |||
28 | public function user() |
||
32 | |||
33 | public function song() |
||
37 | |||
38 | /** |
||
39 | * Increase the number of times a song is played by a user. |
||
40 | * |
||
41 | * @param string $songId |
||
42 | * @param User $user |
||
43 | * |
||
44 | * @return Interaction |
||
45 | */ |
||
46 | View Code Duplication | public static function increasePlayCount($songId, User $user) |
|
60 | |||
61 | /** |
||
62 | * Like or unlike a song on behalf of a user. |
||
63 | * |
||
64 | * @param string $songId |
||
65 | * @param User $user |
||
66 | * |
||
67 | * @return Interaction |
||
68 | */ |
||
69 | View Code Duplication | public static function toggleLike($songId, User $user) |
|
81 | |||
82 | /** |
||
83 | * Like several songs at once. |
||
84 | * |
||
85 | * @param array $songIds |
||
86 | * @param User $user |
||
87 | * |
||
88 | * @return array |
||
89 | */ |
||
90 | public static function batchLike(array $songIds, User $user) |
||
108 | |||
109 | /** |
||
110 | * Unlike several songs at once. |
||
111 | * |
||
112 | * @param array $songIds |
||
113 | * @param User $user |
||
114 | * |
||
115 | * @return int |
||
116 | */ |
||
117 | public static function batchUnlike(array $songIds, User $user) |
||
126 | } |
||
127 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.