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 |
||
| 5 | trait SortedSetBehavior |
||
| 6 | { |
||
| 7 | /** |
||
| 8 | * Add one or more members to a sorted set, or update its score if it already exists |
||
| 9 | * @param string $key |
||
| 10 | * @param array $dictionary (score1, member1[, score2, member2]) or associative array: [member1 => score1, member2 => score2] |
||
| 11 | * @return int |
||
| 12 | */ |
||
| 13 | 20 | public function zadd($key, ...$dictionary) |
|
| 26 | |||
| 27 | /** |
||
| 28 | * Return a range of members in a sorted set, by index |
||
| 29 | * @param string $key |
||
| 30 | * @param int $start |
||
| 31 | * @param int $stop |
||
| 32 | * @param boolean $withscores |
||
| 33 | * @return array |
||
| 34 | */ |
||
| 35 | 4 | View Code Duplication | public function zrange($key, $start, $stop, $withscores = false) |
| 43 | |||
| 44 | /** |
||
| 45 | * Return a range of members in a sorted set, by index, with scores ordered from high to low |
||
| 46 | * @param string $key |
||
| 47 | * @param int $start |
||
| 48 | * @param int $stop |
||
| 49 | * @param boolean $withscores |
||
| 50 | * @return array |
||
| 51 | */ |
||
| 52 | 4 | View Code Duplication | public function zrevrange($key, $start, $stop, $withscores = false) |
| 60 | } |
||
| 61 |
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.