1.2.407. Else Usage¶
Else can be avoided by various means.
For example, defaulting values before using a condition; returning early in the method, thus skipping long else blocks; using a ternary operator to assign values conditionnaly.
Else is the equivalent of the default clause in a switch statement. When the if/then structure can be replaced with a switch can (albeit, a 2-case switch seems strange), then else usage is a good solution.
<?php
// $a is always set
$a = 'default';
if ($condition) {
$a = foo($condition);
}
// Don't use else for default : set default before
if ($condition) {
$a = foo($condition);
} else {
$a = 'default';
}
// Use then to exit
if ( ! $condition) {
return;
}
$a = foo($condition);
// don't use else to return
if ($condition) {
$a = foo($condition);
} else {
return;
}
?>
See also Avoid Else, Return Early and Why does clean code forbid else expression.
1.2.407.1. Connex PHP features¶
1.2.407.1.1. Specs¶
Short name |
Structures/ElseUsage |
Rulesets |
|
Exakat since |
0.8.4 |
PHP Version |
All |
Severity |
|
Time To Fix |
|
Precision |
Very high |
Available in |