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 |
||
22 | class Model extends Relationships implements ModelInterface, RelationshipsInterface |
||
23 | { |
||
24 | /** |
||
25 | * getALL() |
||
26 | * Get all record from the database |
||
27 | * |
||
28 | * @return object |
||
29 | */ |
||
30 | View Code Duplication | public function getAll($dbConnection = NULL) |
|
42 | |||
43 | /** |
||
44 | * where($data, $condition) |
||
45 | * Get data from database where $data = $condition |
||
46 | * |
||
47 | * @return object |
||
48 | */ |
||
49 | public function where($data, $condition = NULL, $dbConnection = NULL) |
||
62 | |||
63 | /** |
||
64 | * find($value) |
||
65 | * Find data from database where id = $value |
||
66 | * |
||
67 | * @return array |
||
68 | */ |
||
69 | public static function find($value, $dbConnection = NULL) |
||
84 | |||
85 | /** |
||
86 | * save() |
||
87 | * Insert data into database |
||
88 | * |
||
89 | * @return bool |
||
90 | */ |
||
91 | View Code Duplication | public function save($dbConnection = NULL) |
|
103 | |||
104 | /** |
||
105 | * update() |
||
106 | * Update details in database after ::find(2) |
||
107 | * |
||
108 | * @return bool |
||
109 | */ |
||
110 | View Code Duplication | public function update($id, $dbConnection = NULL) |
|
111 | { |
||
112 | $connection = DatabaseQuery::checkConnection($dbConnection); |
||
113 | |||
114 | $updateQuery = $this->updateQuery(self::getTableName($connection), $id); |
||
115 | $statement = $connection->prepare($updateQuery); |
||
116 | if ($statement->execute()) { |
||
117 | return true; |
||
118 | } |
||
119 | throw new DataAlreadyExistException(); |
||
120 | } |
||
121 | |||
122 | /** |
||
123 | * destroy($value) |
||
124 | * Delete data from database |
||
125 | * |
||
126 | * @return bool |
||
127 | */ |
||
128 | public function destroy($value, $dbConnection = NULL) |
||
140 | } |
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.