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 | class UserMatcher extends RepositoryMatcher implements KeyMatcherInterface |
||
| 10 | { |
||
| 11 | use FlexibleKeyMatcherTrait; |
||
| 12 | |||
| 13 | const MATCH_USER_ID = 'user_id'; |
||
| 14 | const MATCH_USER_LOGIN = 'login'; |
||
| 15 | const MATCH_USER_EMAIL = 'email'; |
||
| 16 | |||
| 17 | protected $allowedConditions = array( |
||
| 18 | self::MATCH_AND, self::MATCH_OR, |
||
| 19 | self::MATCH_USER_ID, self::MATCH_USER_LOGIN, self::MATCH_USER_EMAIL, |
||
| 20 | // aliases |
||
| 21 | 'id' |
||
| 22 | ); |
||
| 23 | protected $returns = 'User'; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * @param array $conditions key: condition, value: int / string / int[] / string[] |
||
| 27 | * @return UserCollection |
||
| 28 | */ |
||
| 29 | public function match(array $conditions) |
||
| 33 | |||
| 34 | /** |
||
| 35 | * @param array $conditions key: condition, value: int / string / int[] / string[] |
||
| 36 | * @return UserCollection |
||
| 37 | */ |
||
| 38 | public function matchUser(array $conditions) |
||
| 67 | |||
| 68 | /** |
||
| 69 | * NB: bad luck if user login contains an email or otherwise @ character |
||
| 70 | * @param string $key |
||
| 71 | * @return array |
||
| 72 | */ |
||
| 73 | protected function getConditionsFromKey($key) |
||
| 83 | |||
| 84 | /** |
||
| 85 | * @param int[] $userIds |
||
| 86 | * @return User[] |
||
| 87 | */ |
||
| 88 | protected function findUsersById(array $userIds) |
||
| 101 | |||
| 102 | /** |
||
| 103 | * @param string[] $logins |
||
| 104 | * @return User[] |
||
| 105 | */ |
||
| 106 | protected function findUsersByLogin(array $logins) |
||
| 119 | |||
| 120 | /** |
||
| 121 | * @param string[] $emails |
||
| 122 | * @return User[] |
||
| 123 | * |
||
| 124 | * @todo check if this fails when user is not found |
||
| 125 | */ |
||
| 126 | protected function findUsersByEmail(array $emails) |
||
| 141 | } |
||
| 142 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.