When fetching data from another module, or resource, or system, we often check if we actually got a value to avoid errors down the line. This is usually done using null checking. Null Pointer pattern is a design pattern the enables the developer to skip the check and proceed immediately with the program logic without expecting any errors to appear due to the lack of value to work on!
Null Pointer pattern is done by having a method or expression return a non-null value when returning an empty state. Perfect examples in the Java Standard API are:
- Empty string (
""
) forString
Optional.empty()
forOptional
- Empty collections and streams, such as
emptyList()
,emptyMap()
,Stream.empty()
, etc... nullReader()
andnullWriter()
for file I/O
When receiving such values, it is possible to perform standard operations of their respective types without getting any type of error including the infamous NullPointerException
. This is possible because these values are not true null pointers; they are a representation of an empty state. Just continue on working with the program logic without bothering if the value is null or not!
Doing this will result to an empty response but the biggest benefit it offers is that the Null Pointer pattern lessens the program branches. With less branches, there will be less complexity, less scenarios to consider, and less unit tests to write!