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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With