views:

69

answers:

1

To avoid NullPointerExceptions I find it useful to provide an immutable dummy implementation of an interface together with the interface. Like this:

public interface Action {

  void perform();

  public static final Action dummy = new Action() {
    public void perform() { 
      /*nothing*/ 
    }
  };

}

Action.dummy can then be used instead of the evil null.

Is there a name for this design pattern?

+5  A: 

Null Object pattern (provided by M. Fowler if I remember correctly).

Here is a chapter Introduce Null Object from Fowler's Refactoring book.

Roman
@Roman. Yes, Fowler popularized this one in various publications, altho he called it a SpecialCase in PoEAA, which I like even better. Typically a business app will find there is actually useful behavior that goes with an object wanting to be null, if you look for it too.
Berryl
I find "SpecialCase" pretty meaningless. A special case could be everything and nothing, whereas "Null Object" is more meaningful.
deamon