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 |
||
| 12 | class UsersService extends Base |
||
| 13 | { |
||
| 14 | /** |
||
| 15 | * Constructor of the class. |
||
| 16 | * |
||
| 17 | * @param object $database |
||
| 18 | */ |
||
| 19 | public function __construct(\PDO $database) |
||
| 23 | |||
| 24 | /** |
||
| 25 | * Check if the user exists. |
||
| 26 | * |
||
| 27 | * @param int $userId |
||
| 28 | * @return object $user |
||
| 29 | * @throws \Exception |
||
| 30 | */ |
||
| 31 | View Code Duplication | public function checkUser($userId) |
|
|
1 ignored issue
–
show
|
|||
| 32 | { |
||
| 33 | $repo = new UsersRepository; |
||
| 34 | $stmt = $this->database->prepare($repo->getUserQuery()); |
||
| 35 | $stmt->bindParam('id', $userId); |
||
| 36 | $stmt->execute(); |
||
| 37 | $user = $stmt->fetchObject(); |
||
| 38 | if (!$user) { |
||
| 39 | throw new \Exception(self::USER_NOT_FOUND, 404); |
||
| 40 | } |
||
| 41 | |||
| 42 | return $user; |
||
| 43 | } |
||
| 44 | |||
| 45 | /** |
||
| 46 | * Get all users. |
||
| 47 | * |
||
| 48 | * @return array |
||
| 49 | */ |
||
| 50 | public function getUsers() |
||
| 59 | |||
| 60 | /** |
||
| 61 | * Get one user by id. |
||
| 62 | * |
||
| 63 | * @param int $userId |
||
| 64 | * @return array |
||
| 65 | */ |
||
| 66 | public function getUser($userId) |
||
| 72 | |||
| 73 | /** |
||
| 74 | * Search users by name. |
||
| 75 | * |
||
| 76 | * @param string $str |
||
| 77 | * @return array |
||
| 78 | * @throws \Exception |
||
| 79 | */ |
||
| 80 | View Code Duplication | public function searchUsers($str) |
|
| 95 | |||
| 96 | private function validateInput($input) |
||
| 116 | |||
| 117 | /** |
||
| 118 | * Create a user. |
||
| 119 | * |
||
| 120 | * @param array $input |
||
| 121 | * @return array |
||
| 122 | * @throws \Exception |
||
| 123 | */ |
||
| 124 | public function createUser($input) |
||
| 139 | |||
| 140 | /** |
||
| 141 | * Update a user. |
||
| 142 | * |
||
| 143 | * @param array $input |
||
| 144 | * @param int $userId |
||
| 145 | * @return array |
||
| 146 | * @throws \Exception |
||
| 147 | */ |
||
| 148 | View Code Duplication | public function updateUser($input, $userId) |
|
| 169 | |||
| 170 | /** |
||
| 171 | * Delete a user. |
||
| 172 | * |
||
| 173 | * @param int $userId |
||
| 174 | * @return array |
||
| 175 | */ |
||
| 176 | public function deleteUser($userId) |
||
| 187 | } |
||
| 188 |
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.