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 namespace Modules\Core\Console\Installers\Scripts; |
||
9 | class ConfigureDatabase implements SetupScript |
||
10 | { |
||
11 | /** |
||
12 | * @var |
||
13 | */ |
||
14 | protected $config; |
||
15 | |||
16 | /** |
||
17 | * @var EnvFileWriter |
||
18 | */ |
||
19 | protected $env; |
||
20 | |||
21 | /** |
||
22 | * @param Config $config |
||
23 | * @param EnvFileWriter $env |
||
24 | */ |
||
25 | public function __construct(Config $config, EnvFileWriter $env) |
||
30 | |||
31 | /** |
||
32 | * @var Command |
||
33 | */ |
||
34 | protected $command; |
||
35 | |||
36 | /** |
||
37 | * Fire the install script |
||
38 | * @param Command $command |
||
39 | * @return mixed |
||
40 | */ |
||
41 | public function fire(Command $command) |
||
69 | |||
70 | /** |
||
71 | * @return string |
||
72 | */ |
||
73 | protected function askDatabaseHost() |
||
79 | |||
80 | /** |
||
81 | * @return string |
||
82 | */ |
||
83 | View Code Duplication | protected function askDatabaseName() |
|
94 | |||
95 | /** |
||
96 | * @param |
||
97 | * @return string |
||
98 | */ |
||
99 | View Code Duplication | protected function askDatabaseUsername() |
|
110 | |||
111 | /** |
||
112 | * @param |
||
113 | * @return string |
||
114 | */ |
||
115 | protected function askDatabasePassword() |
||
121 | |||
122 | /** |
||
123 | * @param $name |
||
124 | * @param $user |
||
125 | * @param $password |
||
126 | */ |
||
127 | protected function setLaravelConfiguration($name, $user, $password, $host) |
||
134 | |||
135 | /** |
||
136 | * Is the database connection valid? |
||
137 | * @return bool |
||
138 | */ |
||
139 | protected function databaseConnectionIsValid() |
||
149 | } |
||
150 |
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: