Defending the ternary operator

Andrew Dalke adalke at mindspring.com
Mon Feb 10 03:31:28 EST 2003


Paul Rubin:
> I mean the original version was clearer than the rewrite.

Ahh, okay.  Just to make it clear, you find

  if (flg != 1 && cursor && (cursor.dirty() ? !flg : flg) {

more clear than

 if ((flg == 0 and cursor and cursor.dirty()) or
     (flg == 2 and cursor and not cursor.dirty()):

I had to scan the first one several times to understand what
it was doing.  In the real code, the description of the
states flg can take was about 20 lines previous.

> If I remember correctly, I liked the original versions better than the
> rewrites in most but not all of the examples.  I didn't feel like
> going on analyzing every last one of them.

Some of the examples were appropriate but unneeded, like
    n = arr == NULL ? 0 : arr->maxVal();
    // skip a couple lines, then
   head = arr->GetNext(index, n)

where if arr is NULL then the other function would cause a
dereference through NULL.

Others were correct but they data structure used was incorrect.
For example,
  return if_invert ? -val : val;
uses a boolean flag for "if_invert" but could/should use an
inversion factor, as in
  return inversion_factor * val

So yes, the use was appropriate for several of these, in
the limited scope of what it does, but in the larger scale
it was simplifying code which was actually overly complicated
for other reasons.  It was hiding poor construction.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list