Whenever you want to return a value from a method, but whatever you return depends on some other value, you typically use branching:
int calculateSomething() {
if (a == b) {
return x;
} else {
return y;
}
}
Another way to write this is:
int calculateSomething() {
if (a == b) {
return x;
}
return y;
}
Is there any reason to avoid one or the other? Both allow adding "else if"-clauses without problems. Both typically generate compiler errors if you add anything at the bottom.
Note: I couldn't find any duplicates, although multiple questions exist about whether the accompanying curly braces should be on their own line. So let's not get into that.
Best Answer
I use both, depending on the method. For example, in a method that decides something, i think that
captures the intent of the method better. It is stateless, it is not supposed to be extended, and it is closed in that the if-clause generates all values the method may ever return.
If the method calculates something, or retrieves information, i like the second variant more:
Here, the fact that one answer is chosen over the other depends on the state of the answerService. We might extend the method later by adding a preciseAnswerCache, or retrieve the answer from somewhere else.