Just wondering if there is any difference between a series of if
statements separated out from one another, versus a bunch of nested if
statements where each one is indented in from the previous?
Is the same fall through applicable?
There are several styles of if
/else
statements.
1: "Bushy":
if(cond1)
{
if(cond2)
{
if(cond3)
action123;
else action123b;
}
else {
if(cond3b)
action12b3;
else action12b3b;
}
}
else {
/* ... */
}
2: Long if/else chain:
if(cond1)
{
action 1;
}
else if(cond2)
{
action 2;
}
else if(cond3)
{
action 3;
}
else if(cond4)
/* ... */
3: Long if/else chain with "rigid" indentation:
if(cond1)
{
action 1;
}
else {
if(cond2)
{
action 2;
}
else {
if(cond3)
{
action 3;
}
else {
/* ... */
As far as I'm concerned, the general consensus on good programming style is that "bushy" trees like #1 are poor — they can be very hard to understand. (They're barely understandable if they're 2 levels deep, difficult to understand at three, and essentially impossible at 4.)
The general consensus is that a long if/else chain as in #2 is much, much easier to understand. It's such an obvious idiom that it's worth presenting it the way I did in #2, not the more "logical" presentation as in #3.
Bushy trees can be so hard to understand that I sometimes convert them into the chained if/else form:
if(cond1 && cond2)
{
/* action if both true */
}
else if(cond1 && !cond2)
{
/* action if only cond1 true */
}
else if(!cond1 && cond2)
{
/* action if only cond2 true */
}
else {
/* action if neither true */
}
This is "less efficient" in that cond1
and cond2
might be evaluated multiple times, but in doing so it trades off CPU cycles (which are cheap) against programmer time (which is expensive) and bugs (which can be even more expensive).