Effective Java with Groovy - The (in)famous null
If you have seen some of the enterprise applications written in Java, you know the amount of code goes into performing null checks. The 'null reference' feature of Java for sure is the #1 contributor to employment generation. The creator of null reference has already admitted that it was a billion-dollar mistake. Check his presentation here
A well-designed API will mostly confine the null checks to its boundary and leave the rest of the pieces free from the clutter created by null checks. A bit of good advice from 'Effective Java' comes handy here. If your methods return collection types, ensure that you never return null. Instead, you return an empty collection to indicate the absence of values.
Let's take a look at how Groovy helps you from those developers who want to cause trouble to you by writing methods that return null for collection types.
If you are new to Groovy, you might want to get a taste of Groovy from this post.
Consider the following code.
List<Speaker> getSpeakers(String conference) {
return null
}
Suppose someone in your team has written the above method without following the good practices of Effective Java. Say, you are trying to invoke the method as follows.
println getSpeakers('GR8Conf')
.collect { it.firstName }
println getSpeakers('GR8Conf')
.findAll { it.presentationsDelivered > 9 }
First, you are trying to get the first names of speakers. Since getSpeakers
method returns null, typically you would expect this code to throw NullPointerException
. However, you will be pleasantly surprised to see this code return an empty list. This exact behaviour would have occurred had your friend written the code to return an empty list instead of null.
If you are wondering how did this happen, Groovy under the hood uses org.codehaus.groovy.runtime.NullObject
to represent null. When you invoke the iterator
method on NullObject
, it will return an iterator from an empty list. As a result of this, you are saved from writing the code for null checks.
Note that if you try to invoke other methods, you will encounter NullPointerException
as usual. For example, consider the following code.
println demo.getSpeakers('GR8Conf').size() // throws NPE
You can fix the above code by applying the identity transformation as follows.
println getSpeakers('GR8Conf').collect().size() // returns 0
We have seen how Groovy helps its users by automatically applying the Effective Java suggestion on returning null references.
If you are interested in learning more about how Effective Java applies to Groovy code, you may want to take a look at my GR8Conf EU presentation.
To learn more about Effective Java with Groovy, refer to the collection of posts here.
References: