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.