Wednesday, October 10, 2012

Design Pattern: NullObject


Null Object Pattern is one of good pattern used to avoid NullPointerException.
Null Object is not ‘null’ i.e. it is not default value used for object references.

Problem:
We use the null condtion to check the value is null or not null to avoid Null Pointer Exception But it is not a proper solution because we need to add this check whereever we call a method on our object.
I.e. we need to null check for each object before making the calls finally, unnecessary code and unnecessary checks will be added in our program.

Solution:
Create an object that will do nothing whenever nothing is available for reference.

Let’s see the implementation:

Animal:
public interface Animal {
    public void makeSound();
}

Dog: Actual Animal
public class Dog implements Animal {
    public void makeSound() {
            System.out.println("woof!");
    }
}

NullAnimal: Default Animal
public class NullAnimal implements Animal {
    public void makeSound() {
    }
}

When we know actual animal then we will create that animal class if not applicable we will create NullAnimal with default and it will not do anything.

No comments:

Post a Comment