jan
jan

Reputation: 2830

Does the null object pattern make sense without checks only?

If one still uses checks for a null object according to the null object pattern, is this still legal use of the null object pattern or is one violating it already?

public class Example {

   private static final Example NULL = new Example(new Object());

   public static Example getNull() {
       return NULL;
   }

   private Object member;

   public Example(Object member) {
       this.member = member;
   }
}

public class Manager {
   public operation(Example example) {
      if(Example.getNull().equals(example) == false) {
          doSomething(example);
      }
   }
}

Ideally one would have a null object that could be called directly with doSomething(example) without checks. But if one needs such a check, does it still make sense to avoid null at all?

Upvotes: 0

Views: 168

Answers (3)

robermann
robermann

Reputation: 1722

The public façade's methods, published as the API, should check for not-null params; if one of them is null and you envisioned for it the null object pattern, those methods should replace it with a NULL object instance (which would work as a 'default case') and forward it to the back-end methods, which therefore should have no need to do that check.

Upvotes: 1

Pierre Rust
Pierre Rust

Reputation: 2504

I think it's valid to check for Null as long as it only happens very rarely. If the check is systematic, then you obviously do not get any benefit, but it can be necessary to perform the check on some specific corner case.

On your example, using the pattern would result on the following code :

public class Manager {
   public operation(Example example) {
           example.doSomething(example); // does nothing when example is the Null Object
   }
}

But as doSomething is not a method of your object, it might be necessary to do the check (depending of what this method does, of course).

Upvotes: 0

Harmlezz
Harmlezz

Reputation: 8068

In my opinion the Null Object Pattern should be used to avoid checking if a value is absent or not. The responsibility of the Null Object is to behave correctly in case no value is available. For example, if a method processes each item of a collection, instead of using null if no items are available and checking for null to avoid iteration over each element, use an empty collection as Null Object. This way no special case has to be implemented.

If your code checks for null or if the reference is the Null Object, you do not get any benefit from the Null Object Pattern.

Upvotes: 2

Related Questions