The Null Object Pattern

posted on 08/10/07 at 01:36:20 am by Joel Ross

I'm big into design patterns. Every time I see a new one mentioned, I will usually stop and read about it, which is why I was curious when I saw Jeremy Jarrell mention the Null Object Pattern.

It's an interesting idea. Basically, rather than return null and littering your code with "if (obj != null)" statements after every object retrieval, the method that retrieves the object would return a null object.?A null object is an object that doesn't do anything, but also doesn't throw null reference exceptions. You inherit from an object, override all of the properties and methods, and ensure that when they are called, nothing happens, but also that no exceptions are thrown. This allows your "consumer" code to be cleaner because you dont have to check objects when they are returned. Obviously, you can't use this everywhere, since (in my opinion) most of the time, you actually care if the object is null or not. But in cases where it's not unusual to get a null object back, you could utilize this pattern to make your code a little cleaner.

I'm not sure I can think of a good example where I would use this right now, but I'll keep it in mind in case I ever do - which is one of the benefits of patterns in the first place.

Categories: Development