views:

215

answers:

4

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

+2  A: 

In my opinion, you are right. If you need this sort of functionality, just use null, and do null checking and respond for your null state.

Personally, I only really find this useful where an 'empty' value makes sense and you can run with that, hence avoiding null checks. If you need null value (or invalid value) semantics, then null makes sense (and will throw exceptions if you forget to check for it, instead of silently failing).

Matthew Scharley
+5  A: 

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.

RichardOD
+1  A: 

The purpose of the Null Object pattern is essentially to avoid having to do null checks when you want to call methods on a value that is possibly null. But since you specifically want to deal with nulls as a special case, there's no way around the null check.

Having a null check doesn't necessarily defeat the purpose of the Null Object pattern, as it could help you avoid unnecessary null checks elsewhere in your program.

_jameshales
+1  A: 

Using your null object in this way isn't the Null Object Pattern, if you did want to use the pattern then you could. For example if your object had a Name property, just display that, where the null object displayed your "not found" message as its name... but it might not fit into how you're working.

Iain Hoult