Monday, January 9, 2012

Work it like a chain gang

From time to time I find myself using ternary conditionals to output information in an app. If that made little sense to you, you likely should not be reading this blog.

In groovy, we have something like this:

condition ? 'value if true' : 'value if false'

It get even nicer if you considder this form:

condition ?: 'value if false'

where the true case will just return the condition as the value.

Consider: ?: 'unknown'

which will return author.toString() if it's not false/null or 'unknown'.

I've long thought Ruby lacked that elegance and so often resorted to the very cumbersome ? : 'unknown'

until I stumbled onto this (even more elegant) approach: || 'unknown'

One can take this one step further, and chain them up. The first 'true' output is returned: || book.publisher || 'unknown'

or even

author.books && author.books.first || 'unpublished'

This latter form will prevent "null.first" errors.

1 comment:

  1. I often use the ternary myself. I love it.

    But, although my languages of choice don't have shortcut syntax that I know of, I wouldn't be tempted to use it, if they did. Mainly because I strive for coding clarity of a different sort than a lot of other developers.

    I find that many are more concerned with coding laziness (which they will call clarity - ie. syntax that will save them 2 nanoseconds) or elitism ("I know something about the language that you don't"), which they will also call clarity bizarrely.

    I don't mean this as an accusation, but rather just a broad conversational comment, referring to developers in general.

    The type of clarity I prefer is when a statement is unambiguous even to novices of a language and hence easier to maintain or find skills for in a team. The shortcut syntax above, seeing it for the first time, leaves me wondering what exactly it returns - itself if true, or null if true.

    Obviously one makes more sense than the other, but there are many examples where syntax shortcuts leave the unfamiliar developer having to make an assumption or waste time looking something up - more time than would have been "wasted" had the first developer just used the unabbreviated form of the ternary.

    In closing though, I just want to say, I really like your final solution. The binary operators kick ass. :)