Colin Harrington

Archive for October 30th, 2008

Groovy Elvis Operator?:

by on Oct.30, 2008, under Groovy-Grails

What is this Elvis Operator I vaguely recall?  I’ll get to that just bear with me for a minute. 

In Java I’ve seen too many null checks like the following:

If (something != null) {
    val = something
} else {
    val = defaultValue
}

Its handy to have the Groovy Truth so we don’t have to do null checks.  Instead of writing if (something != null) { ... }  we write if (something) { ... }

Well this type of branching logic is precisely why we have the ternary operator in both Java and Groovy.  I’m surprised that the ternary operator is neglected by many developers.  It turns our 4 lines of if/else logic into a single line like:

val = something ? something : defaultValue

The syntax and logic for the ternary operator is the same in Groovy as it is in Java;  (Condition) ? Value-If-True : Value-If-False   I’m not going to get into a lesson on the ternary operator and you can certainly read more here.

When using the ternary operator I had to repeat the variable something twice to do a simple check;  This isn’t groovy and it definitely doesn’t lend itself to the principles of DRY!  *Queue the Elvis operator*
Instead of writing:  val = something ? something : defaultValue
We write:  val = something ?: defaultValue

A more clear example would be as follows:

def rockstar
def defaultrockstar = rockstar ?: "Elvis Presley"
assert defaultrockstar == "Elvis Presley"

*Thank you Satish for the example

InfoQ also has an excellent example under the section Syntax Additions  :: Elvis Operator.

It is nothing too special but It ends up being closer to how we think about code. Apparently the Elvis Operator was added in Groovy 1.5 and is called the ‘Elvis Operator’ due to its resemblance of Elvis’ trademark hair

I find the Elvis operator useful, but I still find myself frequently repeating myself when dealing with the same variable.

def rockstar
rockstar = rockstar ?: "Elvis Presley"

If we have gone this far with the Elvis Operator, why not go the extra step and introduce something like long-eyed-elvis ?= or call it the Rick Astley Operator

def rockstar
rockstar ?= "Elvis Presley"

This would be effectively the same as:

rockstar = rockstar ? rockstar : "Elvis Presley"
     or
rockstar = rockstar ?: "Elvis Presley"

One more for Good measure … rockstar.

More Reading on the Elvis Operator:

?;-)

6 Comments :, more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!