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 |
||
18 | class Extension extends BaseExtension |
||
19 | { |
||
20 | /** |
||
21 | * {@inheritdoc} |
||
22 | */ |
||
23 | 6 | public function getAlias() |
|
27 | |||
28 | |||
29 | /** |
||
30 | * {@inheritdoc} |
||
31 | */ |
||
32 | 6 | public function getNamespace() |
|
36 | |||
37 | /** |
||
38 | * {@inheritdoc} |
||
39 | */ |
||
40 | 2 | public function getXsdValidationBasePath() |
|
41 | { |
||
42 | 2 | return __DIR__.'/../Resources/config/schema'; |
|
|
|||
43 | } |
||
44 | |||
45 | /** |
||
46 | * {@inheritdoc} |
||
47 | */ |
||
48 | 3 | public function load(array $config, ContainerBuilder $container) |
|
60 | |||
61 | /** |
||
62 | * Configure 'runopencode.doctrine.orm.naming_strategy.underscored_bundle_prefix' naming strategy. |
||
63 | * |
||
64 | * @param ContainerBuilder $container |
||
65 | * @param array $config |
||
66 | * @return Extension $this |
||
67 | */ |
||
68 | 3 | View Code Duplication | private function configureUnderscoredBundlePrefixNamer(ContainerBuilder $container, array $config) |
87 | |||
88 | /** |
||
89 | * Configure 'runopencode.doctrine.orm.naming_strategy.underscored_class_namespace_prefix' naming strategy. |
||
90 | * |
||
91 | * @param ContainerBuilder $container |
||
92 | * @param array $config |
||
93 | * @return Extension $this |
||
94 | */ |
||
95 | 3 | View Code Duplication | private function configureUnderscoredClassNamespacePrefixNamer(ContainerBuilder $container, array $config) |
114 | |||
115 | /** |
||
116 | * Configure 'runopencode.doctrine.orm.naming_strategy.underscored_namer_collection' naming strategy. |
||
117 | * |
||
118 | * @param ContainerBuilder $container |
||
119 | * @param array $config |
||
120 | * @return Extension $this |
||
121 | */ |
||
122 | 3 | private function configureNamerCollection(ContainerBuilder $container, array $config) |
|
144 | } |
||
145 |
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.