Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Which one if better, and why? Eg.

if (conditionA && conditionB) {
   //do something 
} else if (conditionA) {
   //do something else
} else if (condition C) {
   ...
}

or

if (conditionA) {
     if (conditionB) {
       //do something 
    } 
 //do something else
} else if (conditionC) {
   ...
}
share|improve this question

2 Answers

up vote 4 down vote accepted

Given your simple example, I strongly prefer the first option. It makes it obvious that at most one block of code is executed and also specifies the precedence in which the alternatives are considered.

As originally written, your second example doesn't even do the same thing as your first because when both conditionA and conditionB are true it executes both //do something and then //do something else.

I suspect you intended your second option to be:

if (conditionA) {
    if (conditionB) {
        //do something
    } else {
        //do something else
    }
} else if (conditionC) {
    ...
}
share|improve this answer
basically, "do something" has a return statement in it, so if it is executed, else part will never be executed. thanks anyway. – Maggie Aug 10 '11 at 17:16

Here's an alternative, one which I prefer under many circumstances.

if (conditionA && conditionB) {
   //do something 
}

if (conditionA && !conditionB) {
   //do something else
} 

if (!conditionA && condition C) {
   ...
}

For me, else complicates matters. It means I can't reorder or extract clauses as easily. It implies complexity and imposes sequence that are not really required by the problem I'm trying to solve. So if I can eliminate it, I try to. It's useful; it has its place - but I try not to overuse else.

share|improve this answer
2  
I dislike this style because if something changes in the condition of the first if, then you will also need to modify the condition in following ifs – jimreed Aug 10 '11 at 16:27
3  
I don't like this as it is not clear from a quick glance that only one block of code should be execute. If the conditions are correct or (I modify the tested variables in a block) then we could have multiple blocks executed. Now if the is the intent (multiple blocks could be executed) then it is fine. – Loki Astari Aug 10 '11 at 17:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.