RWSD: Don’t abuse the ternary (aka “conditional”) operator

Posted by Andy on June 26, 2009
RWSD, Software Development

This will be my first post in a series I think I’ll call:  “Real-World Software Dev” (RWSD for short).  In my short software development career, I come across some things that I feel compelled to write or rant about.  Some of them might be inspired by something I’ve seen in a book, on the intraweb or heard on a podcast, and others might be things that I’ve come across on my own.  Some of these things might be naive, or not even valid, so cut me some slack…

The first topic I’d like to discuss is the ternary conditional operator, which is available in C-based languages (C, C++, Java, C#, etc.).  This operator is basically a condensed form of:

if (conditional)

With the ternary op, it would look like this:

conditional ? doSomething : doSomethingElse

In the real world, it’s my opinion that there are only a few cases when you should use this operator. I think a good rule of thumb is to only use this one-liner if it is completely obvious what the outcome will be whether it falls into the if statement, or else statement. E.g. if you are using this to set a string to one of two possible values, based on a condition:

string myResult = (isSuccess) ? "Great success!" : "You lose!";

It makes me cringe whenever I see the ternary operator used to call one of two methods, or do some other complex action.

string myResult = (isSuccess) ? GetResult(a, b, c) : GetResult(d, e, f);

My big gripe with this thing is that it’s a one-liner, and IMHO, difficult to read. If you put some error-prone call in one of the blocks and it throws, the stack trace will point out the single line containing the ternary operator, rather than pointing out which method was actually called. It must just be Murphy’s Law, but it seems like methods tend to blow up more often when called via the ternary operator, seemingly in some malicious attempt by the computer to make your life more difficult. To me, the ternary just reeks of old-school C code, not unlike its close friend, the “switch” statement. I’m in the camp of writing more explicit, verbose code as opposed to trying to condense code down to the smallest constructs possible.

Overall, the ternary operator is good for simple if/else assignments, but I’d avoid it for just about anything else.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *