Omitting the else is a good idea in some cases, or not? [closed]

7

I ask myself this question every time I'm coding, because I always worry about leaving my code understandable to other programmers who will be looking at it - and myself, because maybe I will not remember what I did there.

Would it be a good idea to omit else on some occasions, as in this case?

$usuario = Usuario::find($id);

if (is_null($usuario)) {
    return Response::json(['error' => 'Usuário não encontrado');
}


return Response::json(['error' => false, 'usuario' => $usuario]);

Or, for some readability, should I do so?

$usuario = Usuario::find($id);

if (is_null($usuario)) {

    return Response::json(['error' => 'Usuário não encontrado');

} else {

    return Response::json(['error' => false, 'usuario' => $usuario]);

}

How could it be harmful to (or not) the else (in cases such as these to facilitate)?

    
asked by anonymous 18.08.2015 / 21:49

3 answers

1

Depends heavily on the need for logic, depending on could use another way:

if(condicao)
{
   //alguma logica
}
else
{
   //alguma logica
}

return resultado;

But in using else and omit else , it works the same, so if it does not enter if , it automatically goes to the logic below.

    
18.08.2015 / 22:10
1

I did not want to be boring, but I could improve it even more:

$usuario = Usuario::find($id);
//se for nulo, retorna 'false', caso contrário, retorna a mensagem
$msg = (is_null($usuario)) ? false : 'Usuário não encontrado';
return Response::json(['error' => $msg, 'usuario' => $usuario]);

Reducing the code improves understanding and reading. Just like that.

    
18.08.2015 / 21:57
0

What is the function of else ?

  

It is to provide the code that should be executed in case (and only in case) the if condition is not true.

In your example, if the if condition is true, the code after it will never be executed because there is a return within the if , and in case it is not true all the code after the if will always be executed; so the else there is redundant.

If you accept the premise that redundant code is unnecessary, the else in your example is unnecessary.

    
19.08.2015 / 00:44