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 |
||
| 9 | class PostPolicy |
||
| 10 | { |
||
| 11 | use HandlesAuthorization; |
||
| 12 | |||
| 13 | /** |
||
| 14 | * Determine whether the user can view the post. |
||
| 15 | * |
||
| 16 | * @param \App\Models\User $user |
||
| 17 | * @param \App\Post $post |
||
| 18 | * @return mixed |
||
| 19 | */ |
||
| 20 | public function view(User $user, Post $post) |
||
| 39 | |||
| 40 | /** |
||
| 41 | * Determine whether the user can create posts. |
||
| 42 | * |
||
| 43 | * @param \App\Models\User $user |
||
| 44 | * @return mixed |
||
| 45 | */ |
||
| 46 | public function create(User $user) |
||
| 52 | |||
| 53 | /** |
||
| 54 | * Determine whether the user can update the post. |
||
| 55 | * |
||
| 56 | * @param \App\Models\User $user |
||
| 57 | * @param \App\Post $post |
||
| 58 | * @return mixed |
||
| 59 | */ |
||
| 60 | View Code Duplication | public function update(User $user, Post $post) |
|
| 70 | |||
| 71 | /** |
||
| 72 | * Determine whether the user can delete the post. |
||
| 73 | * |
||
| 74 | * @param \App\Models\User $user |
||
| 75 | * @param \App\Post $post |
||
| 76 | * @return mixed |
||
| 77 | */ |
||
| 78 | View Code Duplication | public function delete(User $user, Post $post) |
|
| 88 | } |
||
| 89 |
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.