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