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.
Summary: By using an ELSE IF structure instead of multiple IF we can avoid “combined conditions” ( x<y && y<z ). Instead we can use a simplified condition (y<z). Furthermore ELSE IF is more efficient because the computer only has to check conditions until it finds a condition that returns the value TRUE.
The main reason to use else if is to avoid excessive indentation. Of course both of the pieces of code above are equivalent (which means it's impossible for the latter to be mandatory other than in style guides).
In if, the statements inside the if block will execute, if the condition is true and the control is passed to the next statement after the if block. In the if else, if the condition is true, the statements inside the if block will execute and if the condition is false the statements in the if else block will execute.
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!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With