Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

Edit:

I apologize to those who assumed that these functions were meant to be factories or constructors. They're not, they're just placeholders. The question is more about syntax than "factorying". These functions could as well be lambda.

like image 358
Michael Ekoka Avatar asked Mar 24 '10 01:03

Michael Ekoka


People also ask

Which of the following is not used as conditional statement in Python?

25. Which of the following is not used as conditional statement in Python? Explanation: Python does not have a switch or case statement like other programming languages.

Is IF statement considered a function?

IF is one of logical functions that evaluates a certain condition and returns one value if the condition is TRUE, and another value if the condition is FALSE.


1 Answers

If you want a succinct syntax, several languages allow using the "logical or" for this purpose (C# explicitly provides a coalescing operator, because nulls are not falsy).

Python:

fruit = ( getOrange() or 
          getApple()  or 
          getMango()  or 
          Banana() )

C#:

fruit = getOrange() ?? 
        getApple()  ?? 
        getMango()  ?? 
        new Banana();
like image 105
Jimmy Avatar answered Jan 04 '23 21:01

Jimmy