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:

book.author ?: '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

book.author ? book.author : 'unknown'

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

book.author || 'unknown'

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

book.author || book.publisher || 'unknown'

or even

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

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