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 |
||
25 | class PostController extends Controller |
||
26 | { |
||
27 | /** |
||
28 | * @param int|null $id Post type ID |
||
29 | * @param string|null $slug Post type slug. |
||
30 | * @return string |
||
31 | * @throws \yii\web\NotFoundHttpException |
||
32 | */ |
||
33 | View Code Duplication | public function actionIndex($id = null, $slug = null) |
|
71 | |||
72 | /** |
||
73 | * Displays a single Post model. |
||
74 | * |
||
75 | * @param null $slug Post slug |
||
76 | * @param integer $id Post ID |
||
77 | * @throws \yii\web\NotFoundHttpException |
||
78 | * @return mixed |
||
79 | */ |
||
80 | public function actionView($id = null, $slug = null) |
||
115 | |||
116 | /** |
||
117 | * Finds the Post model based on its primary key value. |
||
118 | * If the model is not found, a 404 HTTP exception will be thrown. |
||
119 | * |
||
120 | * @param integer $id |
||
121 | * @return Post the loaded model |
||
122 | * @throws NotFoundHttpException if the model cannot be found |
||
123 | */ |
||
124 | View Code Duplication | protected function findModel($id) |
|
137 | |||
138 | |||
139 | /** |
||
140 | * Finds the Post model based on its primary key value. |
||
141 | * If the model is not found, a 404 HTTP exception will be thrown. |
||
142 | * |
||
143 | * @param string $slug |
||
144 | * @return Post the loaded model |
||
145 | * @throws NotFoundHttpException if the model cannot be found |
||
146 | */ |
||
147 | View Code Duplication | protected function findModelBySlug($slug) |
|
160 | |||
161 | /** |
||
162 | * Finds the Post model based on its primary key value. |
||
163 | * If the model is not found, a 404 HTTP exception will be thrown. |
||
164 | * |
||
165 | * @param $id |
||
166 | * @throws \yii\web\NotFoundHttpException |
||
167 | * @return PostType the loaded model |
||
168 | */ |
||
169 | protected function findPostType($id) |
||
179 | |||
180 | /** |
||
181 | * Finds the Post model based on its primary key value. |
||
182 | * If the model is not found, a 404 HTTP exception will be thrown. |
||
183 | * |
||
184 | * @param string $slug Post type slug |
||
185 | * @throws \yii\web\NotFoundHttpException |
||
186 | * @return PostType the loaded model |
||
187 | */ |
||
188 | protected function findPostTypeBySlug($slug) |
||
198 | } |
||
199 |
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.