Skip to main content
gamedev.net
🔒 Locked

Thoughts on Null Objects

Started by Clash 2 replies 900+ views
Original Post
Clash
Clash
I''ve been writing a GUI Framework using a Test Driven Approach, and I''m finding lots of situations in which introducing a Null Object would simplify my code quite a bit. I was just wondering what everyone''s thoughts and opinions are about their use. - Jason Citron - www.jasoncitron.net
Jason Citron- Programmer, Stormfront Studios- www.stormfront.com
Zahlman
Zahlman
The null object doesn't have to be used to represent an "invalid" object, it can represent the "lack of any real" object in a place where it's reasonable for that situation to exist. I'm a huge fan of it for this use, largely because I'm a Java programmer and I don't particularly like dealing with exceptions, especially runtime ones (except as a debugging tool).

One pattern I have is, when a base class would normally be abstract, to instead use instances of an unspecified base class as null objects. Then subclasses override mostly blank methods rather than implementing over a "virtual" layer.

E.g.

class Bar {
protected static int[] NO_DATA = new int[0];

protected int[] mydata;
public void wibble() {}
public boolean isTangible() {return false;}
public final int getData() {return mydata;}
// I know that last one isn't a terribly good thing to have in OO code, but it's useful for the example

public final String toString() { return super.toString() + " (" + (isTangible ? "" : "in") + "tangible)"; } // will use the subclass' isTangible() - template/hook methods, whee

}

class FooBar extends Bar {
public void wibble() { // do something!

}
public boolean isTangible() { return true; } // probably true in most subclasses... ?

}

class BarUser {
private Bar mybar;
public BarUser(Bar mybar) { this.mybar = mybar; }
public void wibble() {
mybar.wibble(); // can't throw NullPointerException if we're diligent about using the NullObject pattern.

// If there's no real Bar in place, just returns silently, and probably with less overhead than a try-catch for NPE

doSomeBarUserLevelWibbling();
}
public String toString() { return super.toString + "
which uses " + mybar; }
}


[edit: For large blocks of code, use source instead of code tags]

[edited by - Magmai Kai Holmlor on January 12, 2004 11:02:27 AM]
Shannon Barber
Shannon Barber
Whenever you have a strategy pattern, you''ll probably want such ''do nothing'' objects. They''re not really ''null'' object though, maybe you should called them place-holders?
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.