Tuesday, November 20, 2012

Using NULL constants

I think the Null Object pattern is a good approach to not have null checks in the source code, but I do it a little differently from what is shown at Wikipedia.
First thing - I do not use an interface nor a Null class. Second thing - I use a constant to hold the Null object.
class MyClass {
  public static final MyClass NULL = new MyClass();
}

If I add a method to MyClass that changes the object state I change the NULL initialization to use an inner class.
class MyClass {
  public static final MyClass NULL = new MyClass() {
    public void setAttribute(int newValue) {}

  };

  private int attribute;

  public void setAttribute(int newValue) {
    this.attribute = newValue;

  }
}