Let’s start with the assumption that null is evil. There are a million posts out there on this topic, so I won’t beat a dead horse on that.
Note: I wrote up some source code with unit tests for this example. You can find that here: https://github.com/davidmerrick/defensive-optionals.
Say you have this Cat object. A cat, naturally, can optionally have laser vision.
All good, right? Well, what if you did this?
That Optional parameter is initialized to null. Which sort of defeats the purpose of using an Optional in the first place.
We can solve this by initializing the object to
noLaserVisionByDefault() test passes. But, we’re not quite done. What if someone inadvertently sets that parameter to null?
The way to defend against this is to make the
laserVisionOptional parameter private, then enforce its value via a setter.
Now, even if someone tries to set that parameter to null, it will instead be set to
For extra convenience, we can add an overloaded setter that allows us to just pass in a LaserVision object directly.
Notice that this code is also written defensively by using
- null is bad.
- Defensive coding is good.
- protect your Optional parameters from being null by initializing them and by enforcing their values via setters.