Nelz's Blog

11 April 2008

Heavyweight Syntax

Filed under: Java — nelz9999 @ 11:33

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!

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.