I have an application with a number of interface implementations with an unknown source. I wanted to clean up my source code so that I do not need to write:
A a = AFactory.getImpl();
B b = a.getB();
if(b == null) return;
b.doSomething();
Which becomes very long winded. Should I wrap this object so that A will never return null from getB(); and if that is a good idea, how should I do that, Should I provide an implementation that throws an error like InvalidImplemetationException and force it to be caught.
You should consider using the Null Object Pattern: define a value of
Bthat encapsulates the behaviour you want when you don’t really have aB. In this case that meansdoSomething()does nothing.Bwould look like this:You would use it like this:
If you can change
AFactory.getImpl, have it returnB.NULLinstead ofnull. Then you don’t needB.fromAand you can do this instead: