Best practice in setting return value (use else or?)
Posted
by
Deckard
on Programmers
See other posts from Programmers
or by Deckard
Published on 2011-06-29T07:52:56Z
Indexed on
2011/06/29
8:30 UTC
Read the original article
Hit count: 331
best-practices
|coding-style
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.
© Programmers or respective owner