This method:
boolean containsSmiley(String s) {
if (s == null) {
return false;
}
else {
return s.contains(":)");
}
}
can equivalently be written:
boolean containsSmiley(String s) {
if (s == null) {
return false;
}
return s.contains(":)");
}
In my experience, the second form is seen more often, especially in more complex methods (where there may be several such exit points), and the same is true for "throw" as well as "return". Yet the first form arguably makes the conditional structure of the code more explicit. Are there any reasons to prefer one over the other?
(Related: Should a function have only one return statement?)
It's religious argument and at the end of the day it doesn't matter. I'd even argue that the first form is more readable in some circumstances. If you have large chunks of code in an
if-elseif-elseif-else
, it's easier, at first glance to see what the default return is.Because there is an optional (switched off by default) warning in eclipse if else is used in such situation ;).
The
else
in that case would be redundant, as well as create unnecessary extra indentation for the main code of the function.The first form is simply less verbose - when you return a value you automatically leave the scope of the function you're in and return to the caller, so any of the code thereafter will only execute if the IF statement doesn't evaluate to true and subsequently return anything.
I prefer writing it like this:
I'd argue for readability. If you're scanning screens of code trying to figure out what the code does, it's a visual prompt to the developer.
...but it's not really needed because we all comment our code so well, right? :)