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;



Gaurav Joshi said...
This comment has been removed by a blog administrator.
Thiago said...

I agreed with the use of Null constants, but I need to put those inner classes in all classes?

Telmo Pimentel Mota said...

Add them by demand. If you would write an if != null check, stop and see if that type already has a NULL constant. If you would return null, return a NULL constant instead.