This is more of a style question than an “I’m having trouble question”. For Null placeholder objects (am I using the right term?), is it generally preferred to use the Singleton pattern? For ease of discussion, here’s an example:
public interface Foo {
void myMethod();
}
public class RealFoo implements Foo {
void myMethod() { /* Do something productive */ }
}
public class MyUniverse {
public static void main(String args[]) {
Foo[] fooArray = new Foo[10];
// do something productive that might result in Null objects in the array
for (Foo f : fooArray) {
f.myMethod(); // I DONT WANT TO DO if (f != null) blah blah
}
}
}
Ok so that’s my scenario, is it preferred to do A or B?
// A
public class NullFoo implements Foo {
public NullFoo() {}
public void myMethod() { /* don't need to do anything */ }
}
// B
public class NullFoo implements Foo {
private static NullFoo _instance = null;
protected NullFoo() {}
public static NullFoo getInstance() {
if (_instance == null) _instance = new NullFoo();
return _instance;
}
public void myMethod() { /* don't need to do anything */ }
}
Thanks! My instinct that B is almost always superior but maybe I’m missing something, so I ask…
I would go for the latter. I may be something of a trend-bucker on this, but I don’t see singletons as inherently evil. If a class has no mutable state, a singleton is just fine.
I’d make the constructor private, though, not protected. Also, your lazy loading is race-prone; I would just instantiate NullFoo on the declaration line (
private static final Foo instance = new NullFoo();). And lastly, don’t forget to have the class actually implement the interface. 🙂