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 |
||
10 | final class NoXMLSpace |
||
11 | { |
||
12 | |||
13 | /** |
||
14 | * noSpace |
||
15 | * Remove all spaces in both side of the words in a .xml file |
||
16 | * |
||
17 | * Here is an inline example: |
||
18 | * <code> |
||
19 | * <?php |
||
20 | * $file = simplexml_load_file($_FILES['xml']['tmp_name']); |
||
21 | * $xml = noSpace($xml); |
||
22 | * ?> |
||
23 | * </code> |
||
24 | * |
||
25 | * @param xml |
||
26 | * @return xml |
||
27 | * @access public |
||
28 | */ |
||
29 | public static function noSpace( $xml = null ) |
||
43 | |||
44 | } |
||
45 | |||
48 |
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.