Omitting Else is a good idea in some cases, right?

Asked

Viewed 187 times

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 contemplate it - and myself, because maybe I won’t remember what I did there.

It would 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 the sake of readability, I should 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]);

}

Where the placing (or not) of else (in cases such as these, to facilitate)?

  • 2

    I find that very personal. I prefer to omit the else in such cases. There will be people talking that no one sucks because you should not have more than one return in function.

  • @bfavaretto, I’d rather do this than create a variable called $return and go by assigning the response data to it. This can make it more confusing than the omission of the else in itself. The question is to simplify. If you have two return simplifies, so why not?

  • 2

    I kind of agree with you. I am not one of those fundamentalists of a Return only :) But I think the question is well based on opinion, look at the answer that has already appeared.

  • So in that case, I agree to close my own question @bfavaretto

  • Let’s wait a little longer to see what the others think.

  • @bfavaretto When I was a kid I thought I should have a single Return, until I realized that the problem was not the multiple Returns but the gigantic blocks of code with many responsibilities - in these a Return lost in the middle screwed up with all the same :D

  • There’s another question there: Using multiple Returns is a bad practice?

  • 2

    @Wallacemaxters Here’s an answer: no, it’s not ;-) Method with more than one responsibility is that it’s bad practice. If the method has only one responsibility it is naturally short and the multiple Returns will not harm your expressiveness or cause confusion.

  • 2
  • Although the question prompts opinions, there are many opinions that are good for you to learn to do something useful in programming

  • I always leave one return only. I omit the else when it’s not necessary. I find it aesthetically ugly.

  • 1

    I also omit Else and do not find more than one Return problematic. I am in the opinion of @Caffé: more important than that, is to separate well the responsibilities.

Show 7 more comments

3 answers

1

I don’t mean to be annoying, but I can make it even better:

$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 code improves comprehension and reading. Simply like this.

  • 1

    I disagree. Reducing the code doesn’t always improve comprehension and reading. It’s kind of plastered

  • It is better to follow the normalization, starting from the PSR-4, of http://www.php-fig.org/

  • 1

    But the PHP encoding standard is not PSR-2?

  • Don’t do twice what can be done once.

  • 5

    Well, for me one if ternary is more illegible than a if else normal.

  • Well, the more lines you use in the code, the more lines you’ll have to read. So... to understand the difference between a ternary is a if else, just know that both exist. Obviously that you use the ternary more than once in the same line, will hinder understanding.

  • What I mean is that you can always improve your code so that the machine makes a faster decision for you, it facilitates systemic understanding. A programmer must have the same ability of systemic understanding, this does not necessarily mean writing less readable code to the developer, but uniting the two worlds is ideal. But there is @Annotations and //comments to help understanding and unfortunately few people make use of it, or at least good use of them.

  • 2

    I do not agree that this code is more readable. Even though PHP syntax makes all other alternatives seem overly complex, ternary conditionals are unnecessarily obscure.

  • "If all the rules didn’t work, then we ran away from them". That’s the logic I consider "messy," now that you think it’s best to write it for me whatever, aesthetically, I’d rather use ternário because I’m really boring, "I didn’t want to be anymore," and I like to see everything in the same line. If it will have many rules or conditionals, I prefer to separate them into new methods. I am fully in favor of polymorphism.

Show 4 more comments

1

It depends a lot on the need of logic, depending could use another way:

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

return resultado;

But in using else and omit the else, it’s the same, because if you don’t if, automatically goes to the logic below.

  • 1

    according to http://www.php-fig.org/psr/psr-2/ This formatting is only suitable for classes and methods.

0

What is the function of Else?

Is to provide the code that must be executed in the case of (and only in the case of) the condition of the if not be true.

In your example, in the case of the condition of the if be true, the code after it will never run because there is a Return inside the block if, and in case the entire code is not true after the if will always be executed; hence, the Else there is redundant.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.