Avoiding a null pointer exception state with the null object pattern
The null object pattern provides a way to gracefully deal with an unidentified object and not cause unexpected or undefined program behavior.
Motivation
Instead of using the Java null
construct to indicate the absence of an object, consider introducing the Null object pattern. A null object is considered to belong to a specific family of objects. The object implements the expected interface, but implementing its methods does not cause any actions. The advantage of this approach over using an undefined null reference is that the null object is very predictable and has no side effects: it does nothing. It also attempts to eliminate the unpleasant null pointer exception.
Finding it in the JDK
The traditionally mentioned java.base
module and the Collection
framework, located in the java.util
package, define the Collections
utility class. This class contains an internal private EmptyIterator
class to serve...