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)?
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 onereturn
in function.– bfavaretto
@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 theelse
in itself. The question is to simplify. If you have tworeturn
simplifies, so why not?– Wallace Maxters
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.
– bfavaretto
So in that case, I agree to close my own question @bfavaretto
– Wallace Maxters
Let’s wait a little longer to see what the others think.
– bfavaretto
@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
– Caffé
There’s another question there: Using multiple Returns is a bad practice?
– Wallace Maxters
@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.
– Caffé
Related: Why should I only use a "Return" in each function?
– rray
Although the question prompts opinions, there are many opinions that are good for you to learn to do something useful in programming
– Wallace Maxters
I always leave one
return
only. I omit theelse
when it’s not necessary. I find it aesthetically ugly.– Diego Souza
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.
– cantoni