Why null object design pattern is better than null object check. If we look at the memory footprint in null object design pattern we create a new dummy object of same type. Which show if we have object of big size and large number of nullable objects in search query, this pattern will create that much number of null object which will occupy more memory than a simple check which for null which my cost ignoreable delay in performance.
Null Object design pattern
The whole problem with null
is that if you try to access a null
value the application will throw a NullPointerException
and abort.
To reduce the number of class NullXXX
in this null object design pattern (its actually just the factory design dattern, not a pattern itself) you could make a static final NullCustomer
which is always returned.
In Java 8 you can use the Optional approach in order to tell when a function does not always return values. This approach does not force you to create arbitrary null classes which pollute the overall structure (consider may have to refactor those null classes, too).
Eclipse and IntelliJ also offer compile time annotations @Nullable
, @NonNull
which give compiler warnings when accessing potential null
objects. However, many frameworks are not annotated. IntelliJ therefore tries to discover those potential null accesses with static analysis.
Beside low adoption of this approach IntelliJ and Eclipse use their own annotations (org.eclipse.jdt.annotation.NonNull
, com.intellij.annotations.NotNull
) that those are not compatible. But, you can store the annotations outside of the code which works in IntelliJ. Eclipse want to implement this in the future, too. The problem is that there are many frameworks providing this feature giving you many different annotations doing the very same. There was JSR-305 which is dormant. It'd provide an annotation in javax
. I don't know the reason why they did not pushed this further.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With