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 |
||
23 | class Counter extends ActiveRecord |
||
24 | { |
||
25 | const POSITION_AT_END_OF_BODY = 0; |
||
26 | const POSITION_AT_BEGIN_OF_BODY = 1; |
||
27 | const POSITION_AT_HEAD = 2; |
||
28 | |||
29 | const MESSAGE_END_OF_BODY_TAG = "End of body tag"; |
||
30 | const MESSAGE_BEGINNING_OF_BODY_TAG = "Beginning of body tag"; |
||
31 | const MESSAGE_INSIDE_OF_HEAD_TAG = "Inside of head tag"; |
||
32 | |||
33 | /** |
||
34 | * @inheritdoc |
||
35 | */ |
||
36 | public static function tableName() |
||
40 | |||
41 | /** |
||
42 | * @param $counter |
||
43 | * @return string |
||
44 | */ |
||
45 | private static function renderCounter($counter) |
||
52 | |||
53 | /** |
||
54 | * @inheritdoc |
||
55 | */ |
||
56 | View Code Duplication | public function rules() |
|
65 | |||
66 | public function behaviors() |
||
72 | |||
73 | /** |
||
74 | * @inheritdoc |
||
75 | */ |
||
76 | public function attributeLabels() |
||
77 | { |
||
78 | return [ |
||
79 | 'id' => \Yii::t('app', 'ID'), |
||
80 | 'name' => \Yii::t('app', 'Name'), |
||
81 | 'description' => \Yii::t('app', 'Description'), |
||
82 | 'code' => \Yii::t('app', 'Code'), |
||
83 | 'position' => \Yii::t('app', 'Position') |
||
84 | ]; |
||
85 | } |
||
86 | |||
87 | public static function renderCountersAtHead(Event $event) |
||
94 | |||
95 | public static function renderCountersAtBeginningOfBody(Event $event) |
||
99 | |||
100 | public static function renderCountersAtEndOfBody(Event $event) |
||
104 | |||
105 | /** |
||
106 | * @return string[] |
||
107 | */ |
||
108 | public static function getPositionVariants() |
||
116 | |||
117 | /** |
||
118 | * @param Counter $model |
||
119 | * @return null|string |
||
120 | */ |
||
121 | public static function updateInfoForEditable(Counter $model) |
||
146 | |||
147 | public static function renderCounters(Event $event, $mode = self::POSITION_AT_END_OF_BODY) |
||
178 | |||
179 | public function scenarios() |
||
185 | |||
186 | |||
187 | /** |
||
188 | * Search counters |
||
189 | * @param $params |
||
190 | * @return ActiveDataProvider |
||
191 | */ |
||
192 | public |
||
217 | } |
||
218 |
Let’s assume you have a class which uses late-static binding:
}
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()
on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClass
to useself
instead: