Best practice in setting return value (use else or?)
- by Deckard
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.