Avoid using else
Using else often encourages complexer code structure, makes code less readable. In most cases you can refactor it using early returns.
In this piece of code, it takes some brainpower to determine when those else conditions will be reached.
if ($conditionA) {
if ($conditionB) {
// condition A and B passed
}
else {
// condition A passed, B failed
}
}
else {
// condition A failed
}
Using early returns this becomes much more readable, because there aren't as many nested paths to follow. Our code has become more linear.
if (! $conditionA) {
// condition A failed
return;
}
if (! $conditionB) {
// condition A passed, B failed
return;
}
// condition A and B passed
Flattening code" by removing nested structures makes it so that we don't have to think as hard to understand the possible paths our code can take. It has a significant impact on readability.