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 |
||
14 | class MigrationMakeCommand extends GeneratorCommand |
||
15 | { |
||
16 | use ModuleCommandTrait; |
||
17 | |||
18 | /** |
||
19 | * The console command name. |
||
20 | * |
||
21 | * @var string |
||
22 | */ |
||
23 | protected $name = 'module:make-migration'; |
||
24 | |||
25 | /** |
||
26 | * The console command description. |
||
27 | * |
||
28 | * @var string |
||
29 | */ |
||
30 | protected $description = 'Create a new migration for the specified module.'; |
||
31 | |||
32 | /** |
||
33 | * Get the console command arguments. |
||
34 | * |
||
35 | * @return array |
||
36 | */ |
||
37 | 92 | protected function getArguments() |
|
44 | |||
45 | /** |
||
46 | * Get the console command options. |
||
47 | * |
||
48 | * @return array |
||
49 | */ |
||
50 | 92 | protected function getOptions() |
|
57 | |||
58 | /** |
||
59 | * Get schema parser. |
||
60 | * |
||
61 | * @return SchemaParser |
||
62 | */ |
||
63 | 9 | public function getSchemaParser() |
|
67 | |||
68 | /** |
||
69 | * @throws \InvalidArgumentException |
||
70 | * |
||
71 | * @return mixed |
||
72 | */ |
||
73 | 10 | protected function getTemplateContents() |
|
109 | |||
110 | /** |
||
111 | * @return mixed |
||
112 | */ |
||
113 | 10 | protected function getDestinationFilePath() |
|
121 | |||
122 | /** |
||
123 | * @return string |
||
124 | */ |
||
125 | 10 | private function getFileName() |
|
129 | |||
130 | /** |
||
131 | * @return array|string |
||
132 | */ |
||
133 | 10 | private function getSchemaName() |
|
137 | |||
138 | /** |
||
139 | * @return string |
||
140 | */ |
||
141 | 10 | private function getClassName() |
|
145 | |||
146 | 10 | public function getClass() |
|
150 | |||
151 | /** |
||
152 | * Run the command. |
||
153 | */ |
||
154 | 10 | public function handle() |
|
162 | } |
||
163 |
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.