Search code examples
c#design-patternsnull-object-pattern

Checking invalid state when using Null Object pattern


When using Null Object pattern, how would you 'check' if a situation is invalid? for e.g when there's no item found in the repository, display message 'not found' to the user.

Do I have to do a glorified null check?

  1. if obj.equals(new NullObject()) { showNotFound(); }
  2. if obj.ID.equals( INVALID_ID) { showNotFound(); }

Those techniques seem to defeat the purpose of Null Object pattern itself


Solution

  • The problem is you are using the Null Object pattern in a scenario where there is not neutral behaviour. Adding to what Matthew has stated, using this pattern only makes sense when you want to invoke an operation without worrying that the reference is null.

    c2.com wiki sums it up nicely:

    I have recently come across this issue with the null object pattern (see NullObjectAndRefactoring). My opinion is that if application code needs to check whether it is using a NullObject or not, then the system is no longer using the null object pattern at all, because the NullObject class has been "promoted" from being a mere implementation detail to being a concept in the application domain.