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?)
In my experience, it depends on the code. If I'm 'guarding' against something, I'll do:
The point is clear: If that statement is false, I don't want the function to continue.
On the other hand, there are some functions with multiple options, and in that case I would write it like this:
Even though it could be written as:
It really comes down to which way most clearly shows what the code is doing (not necessarily which bit of code is shortest or has the least indentation).
I would prefer the first option, as it is more human-readable.
As an analogy, compare the next 2 sentences: "If today is raining, then take an umbrella, else take sunglasses." and "If today is raining, then take an umbrella, take sunglasses". The first sentence corresponds to the first block of code from the question, the second one – to the second. The first one is much more clear and readable, isn't it?
The
if
statement is checking/enforcing your contract/expectation of not receiving null values. For that reason, I would prefer to see it separated from the rest of the function as it doesn't have anything to do with the actual logic of what you're trying to accomplish (though this case is very simple).In most cases, though, I prefer code to be as explicit as possible in its intent. If there's something that you can restructure about your function to make it more readable for others, do it. As a professional programmer, your goal should really be to program for those who have to maintain your code after you (including yourself 2 years later...). Anything you can do to help them out is worth doing.
While having an else is correct and there's nothing wrong with it in terms of logic and runnability, I like to avoid the initial WTF moment when the function has no return statement outside of the if/else scope.
Occam's Razor is the principle that "entities must not be multiplied beyond necessity."
Well, some of the reason is just convention, but there is one advantage to the form above...
It's typical when coding a return statement, to make the last statement your default return value. This primarily aids during refactoring - else clauses tend to get wrapped up in other structures, or might accidentally be moved deeper into the tree.