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 |
||
12 | class Date extends DataTypeAbstract implements DataTypeInterface |
||
13 | { |
||
14 | const DATA_TYPE_ERROR = 'Error for value "%s" for "%s" : INVALID_TYPE. Must be a date string.'; |
||
15 | const DATA_FORMAT_ERROR = 'Error for value "%s" for "%s": INVALID_DATE_FORMAT'; |
||
16 | const DATA_MIN_ERROR = 'Error for value "%s" for "%s": MIN_VALUE='; |
||
17 | const DATA_MAX_ERROR = 'Error for value "%s" for "%s": MAX_VALUE='; |
||
18 | |||
19 | protected static $defaults = [ |
||
20 | 'format' => 'Y-m-d H:i:s', |
||
21 | 'default' => 'now', |
||
22 | 'min' => null, |
||
23 | 'max' => null |
||
24 | ]; |
||
25 | |||
26 | protected static $validDateOptions = [ |
||
27 | 'now', |
||
28 | 'tomorrow', |
||
29 | 'next week', |
||
30 | 'next month', |
||
31 | 'next year', |
||
32 | 'yesterday', |
||
33 | 'previous week', |
||
34 | 'previous month', |
||
35 | 'previous year', |
||
36 | ]; |
||
37 | |||
38 | /** |
||
39 | * Date constructor. |
||
40 | * @param string $key |
||
41 | * @param string $datum |
||
42 | * @param array $options |
||
43 | */ |
||
44 | public function __construct(string $key, string $datum, array $options = []) |
||
51 | /** |
||
52 | * {@inheritdoc} |
||
53 | */ |
||
54 | public function assert() |
||
68 | |||
69 | private function checkFormat() |
||
82 | |||
83 | View Code Duplication | private function checkMin() |
|
94 | |||
95 | View Code Duplication | private function checkMax() |
|
106 | /** |
||
107 | * {@inheritdoc} |
||
108 | */ |
||
109 | public function normalize() |
||
120 | } |
||
121 |
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.