What is the purpose of the NullObject class in Groovy?
I've been using Groovy for all of five hours and just came across the Groovy NullObject
. I read t开发者_开发知识库he 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?
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
.
精彩评论