Wednesday, October 31, 2007

Using Groovy to easily avoid nasty NullPointerException

Groovy supports a pretty neat syntactic sugar operator to easily avoid the ugly NullPointerException: the question mark '?'.

Writing this in Java

if (name != null && param1 != null && param1.getUser() != null && name.equals(param1.getUser().getName()))
is now replaced by the much more readable Groovy
if (name && param1 && (name == param1.user?.name))
Amazing how a single character can improve readability that much and avoid potential NPEs. Also if you are curious about my use of == rather than the Java required .equals() see my post on More Groovy Sugar.

Most importantly I have inserted a hidden clue in this post and the first to solve the mystery will receive a free pop of their choice not to exceed 0.77 cents. The winner will be the first commenter with the correct answer.


Sam Jones said...

Last I checked, Equal isn't actually sugar.... ;-)

I'm thinking the ==/.equals() thing is syntactic aspartame.

Sam Jones said...

And since it's aspartame, if you use it too much, you'll get cancer that will spread to your straight-up Java programming, confusing you there.

ba dum tchsh

Joe Kueser said...

I'm not 100% sure, but I *think* you can make:

if (name && param1 && (name == param1.user?.name))

even more readable and use:

if (name && (name == param1?.user?.name))

Joe Kueser said...

Maybe even:

if (name == param1?.user?.name)

Travis Chase said...

Is the hidden clue that you are an uber, leet programming god and deviously handsome as well?

Now give me my Mountain Dew!

products said...

China Wholesale has been described as the world’s factory. This phenomenom is typified by the rise ofbusiness. Incredible range of products available with China Wholesalers “Low Price and High Quality” not only reaches directly to their target clients worldwide but also ensures that wholesale from china from China means margins you cannot find elsewhere and buy products wholesaleChina Wholesale will skyroket your dressescheap naruto cosplayanime cosplaycheap Gemstone Jewelry

products said...

Women’s nike tn Shox Rivalry est le modèle féminin le plus tendance de baskets pour le sport. tn chaussuresConcernant la semelle :spyder jacketsCheap Brand Jeans Shop - True Religion Jeans cheap nike shox & Puma Shoes Online- tn nike,Diesel Jeans le caoutchouc extérieur, l’EVA intermédiaire Levis Jeanset le textile intérieur s’associent pour attribuer à la.ed hardy shirts pretty fitCharlestoncheap columbia jackets. turned a pair of double plays to do the trick.Lacoste Polo Shirts, puma basket, Burberry Polo Shirts.wholesale Lacoste polo shirts and cheap polo shirtswith great price.Thank you so much!!cheap polo shirts men'ssweate,gillette mach3 razor bladesfor men.As for Cheap Evisu JeansCheap Armani Jeanspolo shirtsPuma shoes