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 | View Code Duplication | trait HasPriority |
|
| 9 | { |
||
| 10 | /** |
||
| 11 | * Check the priority of the given model. |
||
| 12 | * |
||
| 13 | * @param string|int|\Chriscreates\Projects\Models\Priority $priority |
||
| 14 | * @return bool |
||
| 15 | */ |
||
| 16 | public function hasPriority($priority) : bool |
||
| 36 | |||
| 37 | /** |
||
| 38 | * Check if the given model has any priority. |
||
| 39 | * |
||
| 40 | * @param array $priorities |
||
| 41 | * @return boolean |
||
| 42 | */ |
||
| 43 | public function hasAnyPriority(array $priorities) : bool |
||
| 49 | |||
| 50 | /** |
||
| 51 | * Set the priority of the given model. |
||
| 52 | * |
||
| 53 | * @param void $priority |
||
| 54 | */ |
||
| 55 | public function setPriority($priority) : void |
||
| 67 | |||
| 68 | /** |
||
| 69 | * Scope - return any model where priority. |
||
| 70 | * |
||
| 71 | * @param \Illuminate\Database\Eloquent\Builder $query |
||
| 72 | * @param string|int|\Chriscreates\Projects\Models\Priority $priority |
||
| 73 | * @return \Illuminate\Database\Eloquent\Builder |
||
| 74 | */ |
||
| 75 | public function scopeWhereHasPriority(Builder $query, $priority) |
||
| 85 | |||
| 86 | /** |
||
| 87 | * Scope - return any model whereIn priorities. |
||
| 88 | * |
||
| 89 | * @param \Illuminate\Database\Eloquent\Builder $query |
||
| 90 | * @param string $key |
||
| 91 | * @param array $priorities |
||
| 92 | * @return \Illuminate\Database\Eloquent\Builder |
||
| 93 | */ |
||
| 94 | public function scopeWhereHasAnyPriority(Builder $query, string $key, array $priorities) |
||
| 100 | } |
||
| 101 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: