Search code examples
coding-styleif-statementnested

nesting if statements


Which is better, nesting an if statement inside the if block, or inside the else block?

a.

if (cond1)
   if (cond2){
      statement1;
      statement2;
      ...
   }
   else {
      statement3;
      statement4;
      ...
   }

else {
   statement5;
   statement6;
   ...
}

b.

if (!cond1) {
   statement5;
   statement6;
   ...
}

else if (cond2) {
   statement1;
   statement2;
   ...
}

else {
   statement3;
   statement4;
   ...
}

Thanks for the replies so far. I just edited the options, but my main concern really is just this: If you have a choice, (by changing the conditional expressions) is it better to nest an if statement in a higher level if's if block or its else block? (a) is just an example of nesting the if in the if block, and (b) is an example of nesting the if in the else block. Thanks again for everyone's time.


Solution

  • EDIT: Thanks for clarifying the question. The question is now really one of style and comes down to what is most readable. Generally speaking the latter is nicer when you have a true multi-way conditional, meaning at some point in the code there are three possible conditions all equally likely and equally sensible. The former is cleaner perhaps when semantically cond1 is the real driver, and cond2 is a kind of subordinate condition that people only think about when cond1 is true.

    OLD ANSWER:

    Here is one interpretation of the question ("nesting inside of then"):

    if (cond1) {
        if (cond2) {
            A
        }
    } else {
        B
    }
    

    This should be written, as Justin points out, as

    if (cond1 && cond2) {
        A
    } else {
        B
    }
    

    unless there is code that needs to be in the if cond1 part that is not in the scope of the if cond2.

    Another interpretation of your question ("nesting inside of else") is:

    if (cond1) {
        A
    } else {
        if (cond2) {
            B
        }
    }
    

    In this case you should rewrite as

    if (cond1) {
        A
    } else if (cond2) {
        B
    }
    

    Because it better expresses the idea of the multiway conditional. Again if there is something that belongs in the scope of not cond1 but not in the scope of the cond2, then you need to nest.

    Hope that helps.