I have this code in a function:
if ($route !== null) { // a route was found
$route->dispatch();
} else {
// show 404 page
$this->showErrorPage(404);
}
Now PHPmd gives an error:
The method run uses an else expression. Else is never necessary and you can simplify the code to work without else.
Now I'm wondering if it really would be better code to avoid the else and just add a return statement to the if part?
PHPMD is expecting you to use an early return statement to avoid the else block. Something like the following.
function foo($access)
{
if ($access) {
return true;
}
return false;
}
You can suppress this warning by adding the following to your class doc block.
/**
* @SuppressWarnings(PHPMD.ElseExpression)
*/
You usually can rewrite the expression to use just an if and it does subjectively make the code more readable.
For example, this code will behave in the same way if showErrorPage breaks the execution of the code.
if ($route == null) {
$this->showErrorPage(404);
}
$route->dispatch();
If the content of your if statement does not break the execution, you could add a return
if ($route == null) {
$this->showErrorPage(404);
return;
}
$route->dispatch();
If you where inside a loop, you could skip that iteration using continue
foreach ($things as $thing ) {
if ($thing == null) {
//do stuff and skip loop iteration
continue;
}
//Things written from this point on act as "else"
}
I wouldn't worry about what PHPmd says , atleast in this case.
They probably meant for you to use the conditional operator because (in their opinion) its 'cleaner'.
$route !== null ? $route->dispatch() : $this->showErrorPage(404) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With