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 |
||
11 | class UsersService extends Base |
||
12 | { |
||
13 | /** |
||
14 | * Constructor of the class. |
||
15 | * |
||
16 | * @param object $database |
||
17 | */ |
||
18 | public function __construct(\PDO $database) |
||
22 | |||
23 | /** |
||
24 | * Check if the user exists. |
||
25 | * |
||
26 | * @param int $userId |
||
27 | * @return object $user |
||
28 | * @throws \Exception |
||
29 | */ |
||
30 | public function checkUser($userId) |
||
43 | |||
44 | /** |
||
45 | * Get all users. |
||
46 | * |
||
47 | * @return array |
||
48 | */ |
||
49 | public function getUsers() |
||
58 | |||
59 | /** |
||
60 | * Get one user by id. |
||
61 | * |
||
62 | * @param int $userId |
||
63 | * @return array |
||
64 | */ |
||
65 | public function getUser($userId) |
||
71 | |||
72 | /** |
||
73 | * Search users by name. |
||
74 | * |
||
75 | * @param string $str |
||
76 | * @return array |
||
77 | * @throws \Exception |
||
78 | */ |
||
79 | View Code Duplication | public function searchUsers($str) |
|
94 | |||
95 | /** |
||
96 | * Create a user. |
||
97 | * |
||
98 | * @param array $input |
||
99 | * @return array |
||
100 | * @throws \Exception |
||
101 | */ |
||
102 | View Code Duplication | public function createUser($input) |
|
121 | |||
122 | /** |
||
123 | * Update a user. |
||
124 | * |
||
125 | * @param array $input |
||
126 | * @param int $userId |
||
127 | * @return array |
||
128 | * @throws \Exception |
||
129 | */ |
||
130 | View Code Duplication | public function updateUser($input, $userId) |
|
151 | |||
152 | /** |
||
153 | * Delete a user. |
||
154 | * |
||
155 | * @param int $userId |
||
156 | * @return array |
||
157 | */ |
||
158 | public function deleteUser($userId) |
||
169 | } |
||
170 |
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.