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 |
||
22 | trait SetterTrait |
||
23 | { |
||
24 | /** |
||
25 | * Set permission. |
||
26 | * @param string $name |
||
27 | * @param string $description |
||
28 | * @return Item |
||
29 | */ |
||
30 | 5 | public function setPermission($name, $description = null) |
|
40 | |||
41 | /** |
||
42 | * Set role. |
||
43 | * @param string $name |
||
44 | * @param string $description |
||
45 | * @return Item |
||
46 | */ |
||
47 | 5 | public function setRole($name, $description = null) |
|
57 | |||
58 | /** |
||
59 | * Set child. |
||
60 | * @param string|Item $parent |
||
61 | * @param string|Item $child |
||
62 | * @return bool |
||
63 | */ |
||
64 | 5 | public function setChild($parent, $child) |
|
86 | |||
87 | /** |
||
88 | * Assigns an item (role or permission) to a user. |
||
89 | * @param string|Item $item |
||
90 | * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) |
||
91 | * @throws \Exception when given wrong item name |
||
92 | * @return Assignment the assignment object |
||
93 | */ |
||
94 | 10 | public function setAssignment($item, $userId) |
|
109 | |||
110 | /** |
||
111 | * Assigns items to a user. |
||
112 | * @param array $items |
||
113 | * @param string|integer $userId |
||
114 | */ |
||
115 | 2 | public function setAssignments(array $items, $userId) |
|
121 | |||
122 | /** |
||
123 | * Returns all assignments in the system. |
||
124 | * @return array |
||
125 | */ |
||
126 | public function getAllAssignments() |
||
130 | |||
131 | /** |
||
132 | * Returns all items in the system. |
||
133 | * @return array |
||
134 | */ |
||
135 | 10 | public function getAllItems() |
|
139 | } |
||
140 |
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.