Monday, December 30, 2013

Groovy's Smooth Operators

Take 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 


The 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 

This 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.

No comments:

Post a Comment