OT2004 : Elegant Implementation of Null Objects

Since Dan and I have both been working together again (2 years at ThoughtWorks) and since I moved into a house less than ten minutes walk from his, we very rarely see each other. So it was good fun to have a geeky catch up session and play with some code.

Something Dan showed me:

interface Something {
Something NULL = (Something)Null.object(Something.class);
// more stuff…
}

The Null class is a simple dynamic proxy that will return an immutable null object that does nothing. Methods that return values will return default primitives (0, false), empty arrays or more dynamic proxies.

So at any point in the code you can call Something.NULL to get the null implementation.

Nice! (Dan, upload it somewhere!)
Update: He did – http://proxytoys.codehaus.org/

  • Trackback are closed
  • Comments (3)
  1. I have an implementation of the NullObject pattern using AspectJ. If the object assignment is due to a null assignment you get a null object (or interface, depending on the assignment). The current implementation captures the stack trace of the original null assignment and then throws an NPE when you try to access it. Don’t like that behaviour – should be easy to change! If you’d like to see the code, pop me an email at dale2003[at]daleasberry[dot]com.

    • Anonymous
    • April 1st, 2004

    Did you know that jMock does this too? A mock with a DefaultResultStub will stub methods that return interface references by returning mocks that also have a DefaultResultStub.

    — Nat.

    • Dude
    • April 1st, 2004

    Could you give an example of how this would be used?

Comments are closed.
%d bloggers like this: