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 |
||
| 21 | trait SetterTrait |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * Set permission. |
||
| 25 | * @param string $name |
||
| 26 | * @param string $description |
||
| 27 | * @return Item |
||
| 28 | */ |
||
| 29 | 7 | public function setPermission($name, $description = null) |
|
| 39 | |||
| 40 | /** |
||
| 41 | * Set role. |
||
| 42 | * @param string $name |
||
| 43 | * @param string $description |
||
| 44 | * @return Item |
||
| 45 | */ |
||
| 46 | 7 | public function setRole($name, $description = null) |
|
| 56 | |||
| 57 | /** |
||
| 58 | * Set child. |
||
| 59 | * @param string|Item $parent |
||
| 60 | * @param string|Item $child |
||
| 61 | * @return bool |
||
| 62 | */ |
||
| 63 | 7 | public function setChild($parent, $child) |
|
| 85 | |||
| 86 | /** |
||
| 87 | * Assigns an item (role or permission) to a user. |
||
| 88 | * @param string|Item $item |
||
| 89 | * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) |
||
| 90 | * @throws \Exception when given wrong item name |
||
| 91 | * @return Assignment the assignment object |
||
| 92 | */ |
||
| 93 | 14 | public function setAssignment($item, $userId) |
|
| 104 | |||
| 105 | 14 | protected function findItem($name, $description = null) |
|
| 117 | |||
| 118 | /** |
||
| 119 | * Assigns items to a user. |
||
| 120 | * @param string|array $items |
||
| 121 | * @param string|integer $userId |
||
| 122 | */ |
||
| 123 | 4 | public function setAssignments($items, $userId) |
|
| 132 | |||
| 133 | /** |
||
| 134 | * Returns all assignments in the system. |
||
| 135 | * @return array |
||
| 136 | */ |
||
| 137 | public function getAllAssignments() |
||
| 141 | |||
| 142 | /** |
||
| 143 | * Returns all items in the system. |
||
| 144 | * @return array |
||
| 145 | */ |
||
| 146 | 14 | public function getAllItems() |
|
| 150 | } |
||
| 151 |
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.