Defending the ternary operator

Andrew Dalke adalke at mindspring.com
Mon Feb 10 12:58:05 EST 2003


John Roth:
> So? I've seen people do things the hard way in
> just about every language I've worked in. In most
> cases, all it takes is a friendly suggestion: "Wouldn't
> this way be clearer?" and they go "Huh? Oh!" and
> the problem goes away.

Answer two questions for me:
  1) C/C++ code has the ?: operator.  Why then do people use
      if (cond) {
        x = val1;
      } else {
        x = val2;
      }
when the expression
      x = cond ? val1 : val2;
is "better"?  Ditto for
      if (cond) {
          return val1;
      }
      return val2;

My limited analysis suggests that the first of these options in
C/C++ is used more often than the second one.  That suggests
to me that the ternary if/else operator is not generally considered
more useful or at least more memorable, than if/else statements.

  2) Suppose you saw some code written
        if cond:
            x = val1
        else:
            x = val2

would you suggest that the Python code always be written
    x = val1 if cond else val2
?  When are the tradeoffs?  Eg, we've already seen some
people say that when the lines get too long it is better written
as an if/else statement rather than an if/else expression, so
the answer is not "always"

Or to generalize #2, when should if/else expression be
used and when should it not be used, and how do you
propogate this sense of style and expectations?

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list