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 |
||
4 | class Setting extends Base { |
||
5 | protected $table = 'settings'; |
||
6 | private $cache = array(); |
||
7 | |||
8 | /** |
||
9 | * Fetch all values available and cache them in this class |
||
10 | * That way we don't fetch them from DB for each call |
||
11 | */ |
||
12 | public function createCache() { |
||
21 | |||
22 | /** |
||
23 | * Flush our local cache, may be required for upgrades |
||
24 | * or other places where we need live data |
||
25 | **/ |
||
26 | public function flushCache() { |
||
30 | |||
31 | /** |
||
32 | * Fetch a value from our table |
||
33 | * @param name string Setting name |
||
34 | * @return value string Value |
||
35 | **/ |
||
36 | public function getValue($name, $default="") { |
||
51 | |||
52 | /** |
||
53 | * Insert or update a setting |
||
54 | * @param name string Name of the variable |
||
55 | * @param value string Variable value |
||
56 | * @return bool |
||
57 | **/ |
||
58 | View Code Duplication | public function setValue($name, $value) { |
|
69 | } |
||
70 | |||
77 |
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.