Why does clean code forbid else expression

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"

    }

Tags:

Php

Phpmd