NHibernate & Null Object Pattern: The Options

Don’t bother using Null Object Pattern

The first option is to just not bother using Null Object Pattern, this is the easiest solution however has the side-effect that you end up with null checks everywhere which is the reason for moving to the Null Object Pattern in the first place.

Place a Null Object in the database

Next option is to have an object in the database that represents the null object so it will probably have an Id of zero and a value of << Unassigned >> or along those lines. This then has its own problems because if it’s a user editable object you don’t really want them to be able to change/delete this data so it becomes a special case that will need to be locked for editing/deleting.

Use Field Access and have the Property Handle the Mismatch

This is my preferred method whereby NHibernate is configured to use field access to the object, and the property handles the mismatch internally for example:

// inside class definition
protected User assignedTo;

public virtual User AssignedTo
        return assignedTo ?? User.NotAssigned;
        if (value == User.NotAssigned)
            assignedTo = null;
            assignedTo = value;

This gives NHibernate a different view of the assigned to value than outside objects, for NHibernate which uses the internal field assignedTo it can be set to a null however for outside objects that have to use the AssignedTo property it will never be a null and instead will be set to the Null Object in this case User.NotAssigned.

Any other options please add a comment below 🙂


3 thoughts on “NHibernate & Null Object Pattern: The Options

  1. Pingback: Web Dev Bros » Blog Archive » Nhibernate and the Null object pattern
  2. I cant get this to work (I am using fluent NHibernate). The property must be virtual, and Fluent does not know how to use the protected one.

    Is there a way to make this work for fluent?

Comments are closed.