Nelz's Blog

Mah blogginess

Heavyweight Syntax

Method chaining seems like such a good idea. And Java supports it, always has. However, if you have been bitten in the butt too often by code you can’t (or don’t) control, you learn the value of defensive programming.

Whereas, I want to write code like this:

public String getDeepString(ComplexObjectA a) {
return a.getComplexObjectB().toString();
}

… I can’t. Or at least it’s not a good idea to write it like that. To protect myself, or classes that utilize my method, I have to write it like this:

public String getDeepString(ComplexObjectA a) {
String result = null;
if (a != null) {
ComplexObjectB b = a.getComplexObjectB();
if (b != null) {
result = b.toString();
}
}
return result;
}

Wash. Rinse. Repeat. Over and over and over, I’m checking for null. And, I’m getting kind of tired of it.

But wait, what light over yon hill breaks? Is it Groovy?!? Groovy provides a fantastic "?." construct, which can reduce the above noisy code to nearly what I was hoping for in my first example:

public String getDeepString(ComplexObjectA a) {
return a?.getComplexObjectB()?.toString();
}

I showed the "Unadulterated Java is so groovy" post to some of my coworkers, and the "?." construct is the single most talked about benefit of potentially adopting Groovy.

No, we haven’t adopted Groovy yet. We’ve got some work to do, including moving toward a Maven (2) build system. But from what I hear the Groovy plugins to Maven and IntelliJ make dropping in Groovy transparent and easy. We may become a Groovy shop yet!