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 Feedback extends ActiveRecord implements ModelInterface |
||
24 | { |
||
25 | const SCENARIO_CONTACT = 'contact'; |
||
26 | const SCENARIO_FEEDBACK = 'feedback'; |
||
27 | |||
28 | /** |
||
29 | * @var string |
||
30 | */ |
||
31 | public $verifyCode; |
||
32 | |||
33 | /** |
||
34 | * {@inheritdoc} |
||
35 | */ |
||
36 | public static function tableName() |
||
40 | |||
41 | /** |
||
42 | * {@inheritdoc} |
||
43 | */ |
||
44 | public function rules() |
||
112 | |||
113 | /** |
||
114 | * Scenarios. |
||
115 | * |
||
116 | * @return array |
||
117 | */ |
||
118 | public function scenarios() |
||
127 | |||
128 | /** |
||
129 | * {@inheritdoc} |
||
130 | */ |
||
131 | public function attributeLabels() |
||
144 | |||
145 | /** |
||
146 | * Returns id of the model. |
||
147 | * |
||
148 | * @return int |
||
149 | */ |
||
150 | public function getId() |
||
154 | |||
155 | /** |
||
156 | * Set read status to "1" after view record. |
||
157 | * |
||
158 | * @param int $id |
||
159 | */ |
||
160 | public static function fixReadStatus(int $id): void |
||
168 | |||
169 | /** |
||
170 | * Sends an email to the specified email address using the information collected by this model. |
||
171 | * |
||
172 | * @param string $email the target email address |
||
173 | * |
||
174 | * @return bool whether the model passes validation |
||
175 | */ |
||
176 | View Code Duplication | public function contact($email) |
|
191 | } |
||
192 |
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_function
expects aPost
object, and outputs the author of the post. The base classPost
returns a simple string and outputting a simple string will work just fine. However, the child classBlogPost
which is a sub-type ofPost
instead decided to return anobject
, and is therefore violating the SOLID principles. If aBlogPost
were passed tomy_function
, PHP would not complain, but ultimately fail when executing thestrtoupper
call in its body.