Saturday, December 23, 2006

NullObject with ObjectRelationMapping

Suppose that Foo and Bar are both class of entity object (an domain object with identity). This is an example of how to use NullObject Pattern with Object Relation Mapping tool.
class Foo {
   public static NULL_FOO_ID = -1;

   public static Foo NULL = new NullFoo() ;

   public static Foo find(long id) {
         Foo result = DB.find(Foo.class, id);
         if( result == null )
             result = NULL;
         return result;
   }

   private long id;

   public long getId() {return id}

   public boolean isNull(){ return false}

   ... // normal behavior
}

class NullFoo extends Foo {
   public boolean isNull(){ return true}

   public long getId() {return NULL_FOO_ID}

   ... // other special behavior
}

class Bar {
   private Foo foo;

   public Foo getFoo(){
      return foo!=null ? foo : Foo.NULL;
   }

   public void setFoo(Foo foo){
      if( foo.isNull() )
          this.foo = null;
      else
          this.foo = foo;
   }
}

No comments: