The NullObjectPattern is intended to be a "safe" ( neutral ) behavior.
The idea is create an object that don't do anything ( but doesn't throw NullPointerException either )
For instance the class defined as:
class Employee {
private String name;
private int age;
public String getName(){ return name; }
public int getAge() { return age; }
}
Would cause a NullPointerException in this code:
class Other {
Employee oscar;
String theName = oscar.getName(); // NPE
}
What the NOP says, is you can have an object like this:
class NullEmployee extends Employee {
public static final Employee instance = new NullEmployee();
public String getName(){ return ""; }
public int getAge() { return 0; }
}
And then use it as the default value.
Employee oscar = NullEmployee.instance;
The problem comes, when you need to repeat the code for every class you create, then a solution would be to have a tool to created it.
Would it be feasible/reasonable/useful to create such a tool or to use it ( if existed )?
Perhaps using AOP or DI the default value could be used automagically.
ImmutableFoo
reference default to the same instance does not create any relationship among theImmutableFoo
references. By contrast, having everyMutableFoo
reference default to the same instance would bind all such references together in a way that wouldn't really make sense. – Cozza