interface Parent{
void process();
}
class Child1 implements Parent{
void process(){
//process by method 1
}
}
class Child2 implements Parent{
void process(){
//process by method 2
}
}
class DummyChild implements Parent{
void process(){
//do nothing
}
}
class D {
Parent getObj(){
if(condition1){
return new Child1();
}
else if(condition2){
return new Child2();
}
else
return new DummyChild();
}
public static void main(String[] args){
Parent obj = getObj();
obj.process();
}
}
In the above code, I have created a DummyChild class so that whenever getObj() is invoked for fetching the correct class object, instead of returning NULL I return the dummyClass object(singleton). This eliminates the NULL check in my code thereby removing the branching because of this condition.
Is this a correct place of using the NULL object pattern or should I use the NULL approach?
java.util.Optional.NullPointerException- this design pattern doesn't stop anyone from passing in anullreference. For robust solution, useOptionalas recommended.Optionalit still forces some branching on the client, which the null pattern doesn’t. There are pros and cons. But we’re turning this question into a more opinion-based one than it was when it was asked.