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 |
||
8 | trait UserAndPermission |
||
9 | { |
||
10 | /** |
||
11 | * USER & PERMISSION |
||
12 | * A model belongs to a Level |
||
13 | * |
||
14 | * @return mixed |
||
15 | */ |
||
16 | public function level() |
||
20 | |||
21 | /** |
||
22 | * USER & PERMISSION |
||
23 | * Assign a model to a level |
||
24 | * |
||
25 | * @param $level |
||
26 | * @return mixed |
||
27 | */ |
||
28 | public function assignLevel($level) |
||
34 | |||
35 | /** |
||
36 | * USER & PERMISSION |
||
37 | * Clear a model's level |
||
38 | * |
||
39 | * @return mixed |
||
40 | */ |
||
41 | public function clearLevel() |
||
45 | |||
46 | |||
47 | /* ------------------------------------------------------------------------------------------------ |
||
48 | | Other Functions |
||
49 | | ------------------------------------------------------------------------------------------------ |
||
50 | */ |
||
51 | /** |
||
52 | * USER & PERMISSION |
||
53 | * Helper function to get the level whether it is the ID |
||
54 | * or the name of the level, or the level object itself. |
||
55 | * |
||
56 | * @param $level |
||
57 | * @return mixed |
||
58 | * @throws LevelNotFoundException |
||
59 | */ |
||
60 | View Code Duplication | protected function getLevel($level) |
|
73 | } |
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.