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 | trait UserAndPermission |
||
10 | { |
||
11 | /** |
||
12 | * USER & PERMISSION |
||
13 | * A model belongs to a Level |
||
14 | * |
||
15 | * @return mixed |
||
16 | */ |
||
17 | 15 | public function level() |
|
21 | |||
22 | /** |
||
23 | * USER & PERMISSION |
||
24 | * Assign a model to a level |
||
25 | * |
||
26 | * @param $level |
||
27 | * @return mixed |
||
28 | */ |
||
29 | 19 | public function assignLevel($level) |
|
35 | |||
36 | /** |
||
37 | * USER & PERMISSION |
||
38 | * Clear a model's level |
||
39 | * |
||
40 | * @return mixed |
||
41 | */ |
||
42 | 2 | public function clearLevel() |
|
46 | |||
47 | /** |
||
48 | * USER & PERMISSION |
||
49 | * First try the cache to return the collection, |
||
50 | * then fetch it from the database. |
||
51 | * |
||
52 | * See @cacheGetLevel() |
||
53 | * |
||
54 | * @return mixed |
||
55 | */ |
||
56 | 3 | public function getLevel() |
|
68 | |||
69 | |||
70 | /* ------------------------------------------------------------------------------------------------ |
||
71 | | Other Functions |
||
72 | | ------------------------------------------------------------------------------------------------ |
||
73 | */ |
||
74 | /** |
||
75 | * USER & PERMISSION |
||
76 | * Return a relationship of the level on a user/permission |
||
77 | * associated to a user by direct or inheritance |
||
78 | * |
||
79 | * @return mixed |
||
80 | */ |
||
81 | 3 | protected function cacheGetLevel() |
|
85 | |||
86 | /** |
||
87 | * USER & PERMISSION |
||
88 | * Helper function to get the level whether it is the ID |
||
89 | * or the name of the level, or the level object itself. |
||
90 | * |
||
91 | * @param $level |
||
92 | * @return mixed |
||
93 | * @throws LevelNotFoundException |
||
94 | */ |
||
95 | 19 | View Code Duplication | protected function getALevel($level) |
108 | } |
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.