Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

The function bar only needs to be called if conditionA is true. But when the result of bar (conditionB) is false, I want to run the code that would have run if conditionA had been false. Is there a more concise way of approaching this without duplication?

var foo;
if(conditionA) {
    var conditionB = bar();
    if(conditionB) {
        foo = a;
    } else {
        foo = b; // duplicate code
    }
} else {
    foo = b;
}
share|improve this question

3 Answers 3

up vote 13 down vote accepted

What about :

var foo;
if(conditionA && bar()) {
    foo = a;
} else {
    foo = b;
} 

Then, if you language has it, you can make this a single statement using the ternary operator :

var foo = (conditionA && bar()) ? a : b;
share|improve this answer
    
Note: this requires short-circuit of logical operators, which most (sane) languages implement. –  skolima Feb 14 '13 at 9:39
1  
Thanks for pointing this out. It actually requires hort-circuit of logical operators or the assumption that bar() is side-effect free. –  Josay Feb 14 '13 at 10:06
1  
@skolima VB.net is probably the most used offender by not defaulting to short circuit evaluation. (You need to use AndAlso/OrAlso to get it.) –  Dan Neely Feb 14 '13 at 13:38
    
Thanks. I'm choosing this as the accepted answer. Though I mistakingly forgot to add that I need to use the truthy result or bar (conditionB) to calculate the the value of foo. Any ideas then? –  Michael Delaney Feb 14 '13 at 15:05
    
Mmm could you please update this question or create a new one to reflect the exact situation ? I'm not quite sure to understand. –  Josay Feb 14 '13 at 21:33

If this is the whole function, or if you're okay with extracting this into a method, you could use early return:

var foo;
if(conditionA) {
    var conditionB = bar();
    if(conditionB) {
        foo = a;
        return;
    }
}
foo = b;

If the repeated code is really just a single line, then it's most likely okay. If it's longer, you can create a separate method for that:

var foo;
if(conditionA) {
    var conditionB = bar();
    if(conditionB) {
        foo = a;
    } else {
        foo = computeB();
    }
} else {
    foo = computeB();
}
share|improve this answer

Something like this:

var foo;
if (conditionA && bar()) {
    foo = a;
} else {
    foo = b;
}

Assuming this is javascript, make sure you're aware of what bar() is returning. If it's not a boolean but a string, number, or object, keep in mind javascript's "truthy" and "falsy" values (i.e. 1, "someVal", {} vs. 0, "", undefined, null)

share|improve this answer

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.