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 string|array $items |
||
| 113 | * @param string|integer $userId |
||
| 114 | */ |
||
| 115 | 2 | public function setAssignments($items, $userId) |
|
| 124 | |||
| 125 | /** |
||
| 126 | * Returns all assignments in the system. |
||
| 127 | * @return array |
||
| 128 | */ |
||
| 129 | public function getAllAssignments() |
||
| 133 | |||
| 134 | /** |
||
| 135 | * Returns all items in the system. |
||
| 136 | * @return array |
||
| 137 | */ |
||
| 138 | 10 | public function getAllItems() |
|
| 142 | } |
||
| 143 |
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
Idableprovides a methodequalsIdthat 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.