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 ?
How do you know which classes to implement? This is a design question, it depends on the application.
Generally speaking the purpose of the NullObject pattern is to support a Replace Conditional with Polymorphism refactoring in the special case where the the conditional is a comparison against the null value of the programming language.
A correct implementation of the example in the video would require delegating the driveCar
method to the Car
classes. The SlowCar
and FastCar
classes would perform the loop, presumably through a shared implementation in a base class, and the NullCar
would just return immediately.
In a Java context, the NullCar.speed
attribute would probably be an unboxed int. So setting it to null
is not an option. I would probably hide the attribute behind accessor, and have NullCar.getSpeed
raise an exception. Any client code that would need a test to avoid this exception would instead move into the car classes.
Delegating all operations that directly depend on a speed value being available is an application of the Tell Don't Ask principle of object-oriented design mentioned by philippe