I am always in the habit of using if, else-if statement instead of multiple if statements.
Example:
int val = -1;
if (a == b1) {
return c1;
} else if (a == b2) {
return c2;
} ...
...
} else {
return c11;
}
How does it compare to example 2:
if (a == b1) {
return c1;
}
if (a == b2) {
return c2;
}
....
if (a == b11) {
return c11;
}
I know functionality wise they are the same. But is it best practice to do if else-if, or not? It’s raised by one of my friends when I pointed out he could structure the code base differently to make it cleaner. It’s already a habit for me for long but I have never asked why.
if-elseif-elsestatements stop doing comparisons as soon as it finds one that’s true.if-if-ifdoes every comparison. The first is more efficient.Edit: It’s been pointed out in comments that you do a
returnwithin eachifblock. In these cases, or in cases where control will leave the method (exceptions), there is no difference between doing multipleifstatements and doingif-elseif-elsestatements.However, it’s best practice to use
if-elseif-elseanyhow. Suppose you change your code such that you don’t do areturnin everyifblock. Then, to remain efficient, you’d also have to change to anif-elseif-elseidiom. Having it beif-elseif-elsefrom 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!).