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 PublishedScope implements Scope |
||
10 | { |
||
11 | /** |
||
12 | * All of the extensions to be added to the builder. |
||
13 | * |
||
14 | * @var array |
||
15 | */ |
||
16 | protected $extensions = ['WithDrafts', 'OnlyDrafts', 'OnlyPublished']; |
||
17 | |||
18 | /** |
||
19 | * Apply the scope to a given Eloquent query builder. |
||
20 | * |
||
21 | * @param \Illuminate\Database\Eloquent\Builder $builder |
||
22 | * @param \Illuminate\Database\Eloquent\Model $model |
||
23 | * |
||
24 | * @return void |
||
25 | */ |
||
26 | 1 | public function apply(Builder $builder, Model $model) |
|
30 | |||
31 | /** |
||
32 | * Extend the query builder with the needed functions. |
||
33 | * |
||
34 | * @param \Illuminate\Database\Eloquent\Builder $builder |
||
35 | * |
||
36 | * @return void |
||
37 | */ |
||
38 | 1 | public function extend(Builder $builder) |
|
44 | |||
45 | /** |
||
46 | * Add the with-drafts extension to the builder. |
||
47 | * |
||
48 | * @param \Illuminate\Database\Eloquent\Builder $builder |
||
49 | * |
||
50 | * @return void |
||
51 | */ |
||
52 | 1 | protected function addWithDrafts(Builder $builder) |
|
58 | |||
59 | /** |
||
60 | * Add the only-published extension to the builder. |
||
61 | * |
||
62 | * @param \Illuminate\Database\Eloquent\Builder $builder |
||
63 | * |
||
64 | * @return void |
||
65 | */ |
||
66 | 1 | View Code Duplication | protected function addOnlyPublished(Builder $builder) |
78 | |||
79 | /** |
||
80 | * Add the only-drafts extension to the builder. |
||
81 | * |
||
82 | * @param \Illuminate\Database\Eloquent\Builder $builder |
||
83 | * |
||
84 | * @return void |
||
85 | */ |
||
86 | 1 | View Code Duplication | protected function addOnlyDrafts(Builder $builder) |
98 | } |
||
99 |
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.