Groovy’s Smooth Operators

smoothoperatprTake a trip back to 1984.  Apple release the Macintosh, ‘The Final Battle‘ is about to commence in V and Scotland win the Five Nations completing a grand slam in the process.  Right in the middle of miners’ strike in the UK, English pop group Sade release the catchy number: Smooth Operator.  It was chart success in the UK and in the US (not to mention the German, Dutch and Austrian charts). Little did Sade know that decades later the Groovy programming language would feature several smooth operators that go above and beyond the standard set of Java operators.  Now, we’ll leave the 1980’s comparisons there and shall discuss a few of the smooth operators in Groovy in this blog post.

Elvis

Elvis-Presley-009The Elvis Operator (so named after a certain person’s hairstyle) is a shortened version of the ternary operator.  It is very handy for null checking. And remember even though it can be argued null handling is bad coding practise because it is better to not have nulls in your code, lots of APIs in a code base will inevitably return nulls and in the real world where you want to add some robustness and defensive coding to keep things smooth in production, this kind of thing can be useful.

Now here is how it works.  If the expression to the left of the Elvis operator evaluates to false (remember in Groovy there are several things such as null, such as an empty String which can be coerced to mean false), the result of the expression will be the whatever is on the right.

String country = country.name ?: "Unknown country"

So, in the above example if country.name is null or just “since both are false in Groovy, country will be assigned as “Unknown country”.   If country.name was not false, country would just be assigned that value.

Null-Safe Dereference (also called the Safe Navigation operator)

This is especially useful to avoid null pointer exceptions in a chained expression. For example,

String location = map.getLocation().getXandYCoordinates();

might yield a null pointer exception. But using the safe navigation operator if either map, or the result of map.getLocation() are null

String location = map?.getLocation()?.getXandYCoordinates();

location will just be set as null. So, no null pointer exception is thrown.

Spread

The Spread operator is useful when executing a method on elements of a collection and collecting the result. In this example, I parse a bunch of Strings into arrays and then run a closure on each of the arrays to get all the first elements.

def names = ["john magoo","peter murphy"]
def namesAsArrays = names*.split(" ")
namesAsArrays.each(){print it[0]}

Now, remember the Spread operator can only be used on methods and on elements. It can’t execute a closure for example. But what we can do is leverage Groovy’s meta programming capabilities to create a method and then use the spread operator to invoke that. Suppose we had a list of numbers that we wanted to add 50 too and then multiply the answer by 6 we could do:

def numbers = [43,4]
java.lang.Integer.metaClass.remixIt = {(delegate + 50) * 6}
numbers*.remixIt()

Spaceship operator

space-shipThis originated in the Perl programming language and is so called because you guessed it, <=> looks like a spaceship!  So how does it work?  Well, it is like this.  The expression on the left and the right of the spaceship operator are both evaluated.   -1 will be returned if the operand on left is smaller, 0 if the left and right are equal and 1 if the left is larger. It’s power should become more obvious with an example.

Say we have a class to represent software engineers.
 
 

class SoftwareEngineer {
    String name
    int age
    String toString() { "($name,$age)" }
}

def engineers = [
    new SoftwareEngineer(name: "Martin Fowler", age: 50),
    new SoftwareEngineer(name: "Roy Fielding", age: 48),
    new SoftwareEngineer(name: "James Gosling", age: 58)
]

Now we could easily sort by age

engineers.sort{it.age}

But what about when our list of Engineers grows and grows and we have multiple engineers of the same age? In these scenarios it would be nice to sort by age first and name second. We could achieve this by doing:

engineers.sort{a, b -> 
   a.age <=> b.age ?: a.name <=> b.name

This expression will try to sort engineers by age first. If their ages’ are equal a.age <=> b.age will return 0. In Groovy and in the Elvis construct, 0 means false and hence a.name <=> b.name will then be evaluated and used to determine the sort.

Field Access

In Groovy, when a field access is attempted, Groovy will invoke the corresponding accessor method. The Field Access operator is a mechanism to force Groovy to use field access.

class RugbyPlayer {
     String name
     String getName() {name ?: "No name"} 
}

assert "Tony" == new RugbyPlayer(name: "Tony").name
assert "No name" == new RugbyPlayer().name
assert null == new RugbyPlayer().@name

Method Reference

The Method Reference operator allows you to treat a reference to a method like a closure.

class MyClass {
   void myMethod() { println "1" }
   void myMethod(String s) { println "2" }
}

def methodRef = new MyClass().&"myMethod"
methodRef()    // outputs 1
methodRef('x') // outputs 2

The .& creates an instance of org.codehaus.groovy.runtime.MethodClosure. This can be assigned to a variable and subsequently invoked as shown.

Happy New Year to you all and hopefully some more blogging in 2014.
 

Reference: Groovy’s Smooth Operators from our JCG partner Alex Staveley at the Dublin’s Tech Blog blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


nine + = 17



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close