I recently watched this youtube tutorial on the Null Object design pattern. Even though there were some errors in it: such as the NullCar that doesn’t do anything creates an infinite loop, the concept was well explained. My question is, what do you do when the objects that can be null have getters, and are used in your code? How do you know which value to return by default? Or should I implement this pattern inside all the objects? What if I need to return strings or primitives? I’m talking from a Java perspective.
EDIT: won’t I be trading null objects testing for default value testing ? If not , why not ?
Answer
As far as I’ve understood it the idea is that the null object’s value is as close to “nothing” as possible. That unfortunately means you have to define it yourself. As an example I personally use “” when I can’t pass a null String, null object number for me is -1 (mostly because by default most database sequences start at 1 and we use those for item id:s a lot so -1 is dead giveaway it’s a null object), with lists/maps/sets it’s Collections.EMPTY_SET
, EMPTY_MAP
or EMPTY_LIST
and so on and so forth. If I have custom class I have to create a null object from, I remove all actual data from it and see where that takes me and then apply what I just mentioned until it’s “empty”.
So you really don’t “know” which value to return by default, you just have to decide it by yourself.