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 Groovyif (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.
5 comments:
Last I checked, Equal isn't actually sugar.... ;-)
I'm thinking the ==/.equals() thing is syntactic aspartame.
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
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))
Maybe even:
if (name == param1?.user?.name)
Is the hidden clue that you are an uber, leet programming god and deviously handsome as well?
Now give me my Mountain Dew!
Post a Comment