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 |
||
5 | class Renderer |
||
6 | { |
||
7 | /** |
||
8 | * @var Singleton The reference to *Singleton* instance of this class |
||
9 | */ |
||
10 | private static $instance; |
||
11 | |||
12 | private $registered_components = array(); |
||
13 | |||
14 | /** |
||
15 | * Returns the *Singleton* instance of this class. |
||
16 | * |
||
17 | * @return Singleton The *Singleton* instance. |
||
18 | */ |
||
19 | public static function get_instance() |
||
27 | |||
28 | public function render_component( $type, array $props = array() ) |
||
33 | |||
34 | |||
35 | /** |
||
36 | * Register a custom component class. If the given component name is similar |
||
37 | * to the name of one of the core components, it will override it. If a |
||
38 | * custom component with a similar name has already been registered, an |
||
39 | * exception will be thrown. |
||
40 | * |
||
41 | * @param string $type |
||
42 | * @param string $class_name |
||
43 | * @throws \RuntimeException |
||
44 | */ |
||
45 | View Code Duplication | public function register_component( $type, $class_name ) |
|
53 | |||
54 | /** |
||
55 | * |
||
56 | * @param type $type |
||
57 | * @param type $props |
||
58 | * @return type |
||
59 | */ |
||
60 | private function create_component( $type, $props ) |
||
70 | |||
71 | /** |
||
72 | * |
||
73 | * @param type $type |
||
74 | * @param type $props |
||
75 | * @throws \RuntimeException |
||
76 | */ |
||
77 | private function create_core_component( $type, $props ) |
||
97 | |||
98 | /** |
||
99 | * |
||
100 | * @param type $type |
||
101 | * @param type $props |
||
102 | * @throws \RuntimeException |
||
103 | */ |
||
104 | View Code Duplication | private function create_registered_component( $type, $props ) |
|
114 | } |
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: