tags:

views:

79

answers:

1

I've been using Groovy for all of five hours and just came across the Groovy NullObject. I read the Groovy explanation of the Null Object Pattern, but it doesn't touch on the NullObject class directly; is NullObject merely intended to be a base class for things like NullTree and NullJob? I'm getting a NullObject back in some code that expects a String, and it's causing a failure much like a "regular" null would have.

So, what is the purpose of NullObject? Or, phrased differently, what value does NullObject offer that "regular" null doesn't?

+4  A: 

Its purpose is to have a null object instead that a null keyword.

In normal Java null is a special keyword that it's used to mean that the reference isn't attached to any object.. this works fine but it doesn't handle situations in which you try to do something with a null reference.

Since a null reference is not an object you can't do anything on it and Java will throw a NullPointerException. On the opposite hand if you have a NullObject your reference will point to this one instead that to nothing.. of course this NullObject is not able to do anything, when you'll try to invoke a method on it nothing will happen but no exception will be thrown because althrough NullObject means "absence of any object" it's implemented as an object with the obvious conseguence to avoid these situations.

So that groovy can handle things like object?.methodName(). If object is null groovy will use a NullObject so that this implicit check will do something like (maybe this is not the actual implementation, is just to give you the idea)

if (object instanceof NullObject)
  return new NullObject();
else
  return object.someMethod();

In conclusion it is needed to overcome the fact that using a null reference in Java will always cause a NullPointerException.

Jack
You say "when you'll try to invoke a method on it nothing will happen but no exception will be thrown"; isn't a silent logical error worse than a NullPointerException?
Lord Torgamus
No, it's not silent because you explictly use the __object?.method()__ syntax just for this purpose. Using the normal syntax __object.method()__ would throw a NullPointerException anyway, also with the null pattern..
Jack
Hm, I need to look into the differences between Java and Groovy more closely, I guess. Reference for future visitors to this question: the operator "?." is named the Safe Navigation Operator. http://groovy.codehaus.org/Statements#Statements-Safenavigation
Lord Torgamus
I love the ?. as well as the ?: operators for "Fun". In my work, I'd prefer to disallow nulls altogether or have a special keyword system (perhaps a "nullable" on anything that can become null--if you switch from nullable to normal you would be forced to do an if(var==null) as part of the switch...) But for groovy scripts at home, these are just pure awesomeness.
Bill K