The Beautiful Ternary

I am a fan of the ternary operator. Yes, it’s alien the first time you meet it, but wow, talk about getting things done! In a single line you can succinctly express a test and two options, making for truly compact yet clear assignments, for example:

var answer = ( condition ? optionOne : optionTwo );

But what if things are a little more complicated? Imagine alternatives involving really long snippets of code or nested options. These could be troubling with inline ternaries, leading to very long lines and complex statements difficult to apprehend at a glance.

But here comes convention to save the day! Consider this interesting use of spaces to visually lay out a ternary statement that would otherwise make for a very long line:

var product = (   determineProductClass( p1 )
                ? configureProductOne( p2, p3, p4, p5 )
                : configureProductTwo( p2, p3 ) );

Putting the three elements of the ternary on three separate lines is pretty common, but adding two spaces to the front of the first element and putting the operators at the front of the latter two lines is less common, I think. The effect, though, is to vertically align the three operands of the ternary, which to me makes the whole thing much more readable and easier to understand, especially if you think of the initial parenthesis and the extra spaces as a signal meaning “here comes a conditional.”

And here the same spacing convention goes wild to illustrate (literally!) a small set of nested options (which could go at least a few layers deeper easily without losing clarity):

var charge = (   product.isShippable()
               ? flatRateShippingCharge +
                 (   product.isOversized()
                   ? oversizedShippingSurcharge
                   : 0 ) // No surcharge for most products!
               : 0 ); // Digital product — no shipping!

Reminds me of the crazy comma first idea (but I’ll leave the tabs-versus-spaces elephant in the room). What do you think? Too weird… or actually helpful?

One response to “The Beautiful Ternary

  1. Hey Jay..I’ve never really done much with Python, but I do enjoy Ruby. You lvnetualey get used to writing loops likeObject.each do |obj| .endwhich is really strange when I spend all my day-job time writing C++. Ruby has a tertiary operator much like C/C++‘s, it’s the one element of familiarity I have when working with it. Just saw the blog in your Facebook profile ‑Kevin

Comments are closed.