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 | View Code Duplication | class UserRepository extends BaseRepository |
|
|
|||
13 | { |
||
14 | /** |
||
15 | * @param object $database |
||
16 | */ |
||
17 | public function __construct(\PDO $database = null) |
||
21 | |||
22 | /** |
||
23 | * Check if the user exists. |
||
24 | * |
||
25 | * @param int $userId |
||
26 | * @return array $user |
||
27 | * @throws \Exception |
||
28 | */ |
||
29 | public function checkUser($userId) |
||
41 | |||
42 | /** |
||
43 | * Get all users. |
||
44 | * |
||
45 | * @return array |
||
46 | */ |
||
47 | public function getUsers() |
||
54 | |||
55 | /** |
||
56 | * Search users by name. |
||
57 | * |
||
58 | * @param string $usersName |
||
59 | * @return array |
||
60 | * @throws \Exception |
||
61 | */ |
||
62 | public function searchUsers($usersName) |
||
75 | |||
76 | /** |
||
77 | * Create a user. |
||
78 | * |
||
79 | * @param array $data |
||
80 | * @return array |
||
81 | * @throws \Exception |
||
82 | */ |
||
83 | public function createUser($data) |
||
93 | |||
94 | /** |
||
95 | * Update a user. |
||
96 | * |
||
97 | * @param array $data |
||
98 | * @param int $userId |
||
99 | * @return array |
||
100 | */ |
||
101 | public function updateUser($data, $userId) |
||
112 | |||
113 | /** |
||
114 | * Delete a user. |
||
115 | * |
||
116 | * @param int $userId |
||
117 | * @return string |
||
118 | */ |
||
119 | public function deleteUser($userId) |
||
127 | } |
||
128 |
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.