Why we use if, else if instead of multiple if block if the body is a return statement
if-elseif-else
statements stop doing comparisons as soon as it finds one that's true. if-if-if
does every comparison. The first is more efficient.
Edit: It's been pointed out in comments that you do a return
within each if
block. In these cases, or in cases where control will leave the method (exceptions), there is no difference between doing multiple if
statements and doing if-elseif-else
statements.
However, it's best practice to use if-elseif-else
anyhow. Suppose you change your code such that you don't do a return
in every if
block. Then, to remain efficient, you'd also have to change to an if-elseif-else
idiom. Having it be if-elseif-else
from the beginning saves you edits in the future, and is clearer to people reading your code (witness the misinterpretation I just gave you by doing a skim-over of your code!).
What about the case where b1 == b2
? (And if a == b1
and a == b2
?)
When that happens, generally speaking, the following two chunks of code will very likely have different behavior:
if (a == b1) {
/* do stuff here, and break out of the test */
}
else if (a == b2) {
/* this block is never reached */
}
and:
if (a == b1) {
/* do stuff here */
}
if (a == b2) {
/* do this stuff, as well */
}
If you want to clearly delineate functionality for the different cases, use if-else
or switch-case
to make one test.
If you want different functionality for multiple cases, then use multiple if
blocks as separate tests.
It's not a question of "best practices" so much as defining whether you have one test or multiple tests.