Avoid null with null object
We all hate duplication, but I think we hate NullPointerException more than duplication and the irony is both happens often or one leads to another.
I had to implement a persistence feature as an optional, and generally when something is optional we usually get the most famous error. NullPointerException and in order to avoid it we do duplication.
We have a Persistence interface and class FooBar has an option to use it. Since it is optional then it could be null, and we hate NPE. In order to avoid NPE, we check whether it is null before using it and then the second annoying situation happens. Duplication.
Did you notice how many times we used persistence != null ? And imagine you have to repeat the same things in many places. If you forget, then you face with NPE.
There is a better solution to avoid all this problems
Null Object Pattern
Since we have default behavior for each method, then why not use them as default instead of checking?
We’ve created a dummy class which implements Persistence and do the default behavior whenever it is called if it is not set and we got rid of all persistence != null checks. Simple and clean.
You can do lazy initialization as well in order to avoid unnecessary GC pause.
What if FooBar instance is created many times?
Which means we will have a new instance of EmptyPersistence as well. We also hate redundant object creation, right?
We could do better, since EmptyPersistence’s state won’t change anytime, then no need to create a new instance for each call. I think this is the only place I would use Singleton. We can basically use the same instance for each FooBar.