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 ManagesStorageConnection |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * @return bool |
||
| 13 | */ |
||
| 14 | public function isReady() |
||
| 22 | |||
| 23 | /** |
||
| 24 | * Sometimes we want to gracefully check up on the cloud storage account without any exceptions |
||
| 25 | */ |
||
| 26 | public function ping() |
||
| 37 | |||
| 38 | /** |
||
| 39 | * @return bool |
||
| 40 | * @throws StorageUnavailableException |
||
| 41 | */ |
||
| 42 | public function verify() |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @return mixed |
||
| 53 | */ |
||
| 54 | public function isConnected() |
||
| 58 | |||
| 59 | /** |
||
| 60 | * @return bool |
||
| 61 | */ |
||
| 62 | public function isEnabled() |
||
| 66 | |||
| 67 | /** |
||
| 68 | * @return bool |
||
| 69 | */ |
||
| 70 | public function isDisabled() |
||
| 74 | |||
| 75 | /** |
||
| 76 | * @return bool |
||
| 77 | */ |
||
| 78 | public function isTokenInvalid() |
||
| 82 | |||
| 83 | /** |
||
| 84 | * @param null $reason |
||
| 85 | * |
||
| 86 | * @return $this |
||
| 87 | */ |
||
| 88 | View Code Duplication | public function disable($reason = null) |
|
| 103 | |||
| 104 | /** |
||
| 105 | * @return $this |
||
| 106 | */ |
||
| 107 | View Code Duplication | public function enable() |
|
| 119 | } |
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.