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 |
||
30 | trait QueryTrait |
||
31 | { |
||
32 | /** |
||
33 | * Returns public users. |
||
34 | * |
||
35 | * @return Eloquent\Collection |
||
36 | */ |
||
37 | 5 | public function activeUsers() |
|
38 | { |
||
39 | 5 | return $this->with('role') |
|
|
|||
40 | 5 | ->where('private', '=', false) |
|
41 | 5 | ->orderBy('firstname', 'ASC')->get(); |
|
42 | } |
||
43 | |||
44 | /** |
||
45 | * Returns user projects with activities details eager loaded. |
||
46 | * |
||
47 | * @param int $status |
||
48 | * |
||
49 | * @return Relations\HasMany |
||
50 | */ |
||
51 | 10 | public function projectsWidthActivities($status = Project::STATUS_OPEN) |
|
75 | |||
76 | /** |
||
77 | * Returns projects with issues details eager loaded. |
||
78 | * |
||
79 | * @param int $status |
||
80 | * |
||
81 | * @return Relations\HasMany |
||
82 | */ |
||
83 | 1 | public function projectsWidthIssues($status = Project::STATUS_OPEN) |
|
101 | |||
102 | /** |
||
103 | * Returns collection of issues grouped by tags. |
||
104 | * |
||
105 | * @param $tagIds |
||
106 | * @param int $projectId |
||
107 | * |
||
108 | * @return mixed |
||
109 | */ |
||
110 | public function issuesGroupByTags($tagIds, $projectId = null) |
||
131 | |||
132 | /** |
||
133 | * Load user permissions. |
||
134 | * |
||
135 | * @return Eloquent\Collection |
||
136 | */ |
||
137 | 62 | protected function loadPermissions() |
|
145 | } |
||
146 |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.