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 |
||
| 11 | class ConfigureDatabase implements SetupScript |
||
| 12 | { |
||
| 13 | /** |
||
| 14 | * @var |
||
| 15 | */ |
||
| 16 | protected $config; |
||
| 17 | |||
| 18 | /** |
||
| 19 | * @var EnvFileWriter |
||
| 20 | */ |
||
| 21 | protected $env; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @param Config $config |
||
| 25 | * @param EnvFileWriter $env |
||
| 26 | */ |
||
| 27 | public function __construct(Config $config, EnvFileWriter $env) |
||
| 32 | |||
| 33 | /** |
||
| 34 | * @var Command |
||
| 35 | */ |
||
| 36 | protected $command; |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Fire the install script |
||
| 40 | * @param Command $command |
||
| 41 | * @return mixed |
||
| 42 | */ |
||
| 43 | public function fire(Command $command) |
||
| 70 | |||
| 71 | /** |
||
| 72 | * @return string |
||
| 73 | */ |
||
| 74 | protected function askDatabaseDriver() |
||
| 79 | |||
| 80 | |||
| 81 | /** |
||
| 82 | * @return string |
||
| 83 | */ |
||
| 84 | protected function askDatabaseHost() |
||
| 90 | |||
| 91 | /** |
||
| 92 | * @return string |
||
| 93 | */ |
||
| 94 | protected function askDatabasePort($driver) |
||
| 99 | |||
| 100 | /** |
||
| 101 | * @return string |
||
| 102 | */ |
||
| 103 | View Code Duplication | protected function askDatabaseName() |
|
| 114 | |||
| 115 | /** |
||
| 116 | * @param |
||
| 117 | * @return string |
||
| 118 | */ |
||
| 119 | View Code Duplication | protected function askDatabaseUsername() |
|
| 130 | |||
| 131 | /** |
||
| 132 | * @param |
||
| 133 | * @return string |
||
| 134 | */ |
||
| 135 | protected function askDatabasePassword() |
||
| 141 | |||
| 142 | /** |
||
| 143 | * @param $driver |
||
| 144 | * @param $name |
||
| 145 | * @param $port |
||
| 146 | * @param $user |
||
| 147 | * @param $password |
||
| 148 | */ |
||
| 149 | protected function setLaravelConfiguration($driver, $host, $port, $name, $user, $password) |
||
| 158 | |||
| 159 | /** |
||
| 160 | * Is the database connection valid? |
||
| 161 | * @return bool |
||
| 162 | */ |
||
| 163 | protected function databaseConnectionIsValid() |
||
| 173 | } |
||
| 174 |
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: