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 Thread extends Model |
||
10 | { |
||
11 | /** |
||
12 | * The attributes that are mass assignable. |
||
13 | * |
||
14 | * @var array |
||
15 | */ |
||
16 | protected $fillable = [ |
||
17 | 'user_id', |
||
18 | 'user_type', |
||
19 | 'channel_id', |
||
20 | 'title', |
||
21 | 'body', |
||
22 | 'view_count', |
||
23 | 'slug' |
||
24 | ]; |
||
25 | |||
26 | protected $guarded = []; |
||
27 | |||
28 | protected $with = ['user', 'channel']; |
||
29 | |||
30 | protected $appends = ['created_at_human_readable']; |
||
31 | |||
32 | /** |
||
33 | * Fetch a path to the current thread. |
||
34 | * |
||
35 | * @return string |
||
36 | */ |
||
37 | public function path() |
||
41 | |||
42 | public function getCreatedAtHumanReadableAttribute() |
||
46 | |||
47 | /** |
||
48 | * A thread belongs to a creator. |
||
49 | * |
||
50 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo |
||
51 | */ |
||
52 | public function user() |
||
56 | |||
57 | public function subscriptions() |
||
61 | |||
62 | public function subscribers() |
||
66 | |||
67 | public function subscribersExcept() |
||
71 | |||
72 | public function channel() |
||
76 | |||
77 | public function replies() |
||
81 | |||
82 | /** |
||
83 | * Add a reply to the thread. |
||
84 | * |
||
85 | * @param $reply |
||
86 | */ |
||
87 | public function addReply($reply, $subscribe=true) |
||
96 | |||
97 | View Code Duplication | public function attachSubscriber($user) |
|
105 | |||
106 | public function detachSubscriber($user) |
||
113 | |||
114 | public function getRouteKeyName() |
||
118 | |||
119 | protected static function boot() |
||
135 | } |
||
136 |
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.