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 |
||
16 | class ProductController extends FController |
||
17 | { |
||
18 | public $pageSize = 10; |
||
19 | |||
20 | 15 | public function behaviors() |
|
21 | { |
||
22 | 15 | return CMap::mergeArray(parent::behaviors(), array( |
|
23 | 15 | 'productTextBehavior' => array('class' => 'backend.modules.product.modules.text.frontend.ProductTextBehavior'), |
|
24 | 15 | 'productFilterBehavior' => array('class' => 'ProductFilterBehavior'), |
|
25 | 'productSortingBehavior' => array( |
||
26 | 15 | 'class' => 'ProductSortingBehavior', |
|
27 | 15 | 'defaultSorting' => 'default', |
|
28 | 15 | 'pageSizeRange' => array(20, 40, 60) |
|
29 | 15 | ) |
|
30 | 15 | )); |
|
31 | } |
||
32 | |||
33 | public function actionCategories() |
||
34 | { |
||
35 | $this->breadcrumbs = array('Производители'); |
||
36 | |||
37 | $categories = ProductCategory::model()->findAll(); |
||
38 | |||
39 | $this->render('categories', array('categories' => $categories)); |
||
40 | } |
||
41 | |||
42 | View Code Duplication | public function actionCategory($category) |
|
|
|||
43 | { |
||
44 | /** |
||
45 | * @var ProductCategory $model |
||
46 | */ |
||
47 | $model = ProductCategory::model()->findByAttributes(array('url' => $category)); |
||
48 | |||
49 | if( !$model ) |
||
50 | throw new CHttpException(404, 'Страница не найдена'); |
||
51 | |||
52 | $this->breadcrumbs = array( |
||
53 | 'Производители' => $this->createUrl('product/categories'), |
||
54 | $model->name, |
||
55 | ); |
||
56 | |||
57 | $criteria = new CDbCriteria(); |
||
58 | $criteria->compare('a.category_id', $model->id); |
||
59 | |||
60 | $this->renderPage(array($model), $criteria); |
||
61 | } |
||
62 | |||
63 | View Code Duplication | public function actionSection($section) |
|
82 | |||
83 | View Code Duplication | public function actionType($type) |
|
102 | |||
103 | public function actionOne($url) |
||
104 | { |
||
105 | /** |
||
129 | |||
130 | public function isFirstPage() |
||
134 | |||
135 | private function renderPage(array $models, CDbCriteria $criteria) |
||
160 | } |
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.