Is it considered bad form to execute a function within a conditional statement?

Posted by michael on Stack Overflow See other posts from Stack Overflow or by michael
Published on 2010-03-24T01:45:32Z Indexed on 2010/03/24 1:53 UTC
Read the original article Hit count: 306

Consider a situation in which you need to call successive routines and stop as soon as one returns a value that could be evaluated as positive (true, object, 1, str(1)).

It's very tempting to do this:

if (fruit = getOrange())
elseif (fruit = getApple())
elseif (fruit = getMango())
else fruit = new Banana();

return fruit;

I like it, but this isn't a very recurrent style in what can be considered professional production code. One is likely to rather see more elaborate code like:

fruit = getOrange();
if(!fruit){
    fruit = getApple();
    if(!fruit){
        fruit = getMango();
        if(!fruit){
            fruit = new Banana();
        }
    }
}

return fruit;

According to the dogma on basic structures, is the previous form acceptable? Would you recommend it?

© Stack Overflow or respective owner

Related posts about if-else-statement

Related posts about conditional