phpphpmd

Why does clean code forbid else expression


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?


Solution

  • 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) ;