Java Reference
In-Depth Information
An important, practical semantic difference in using optionals instead of nulls is that in the first
case, declaring a variable of type Optional<Car> instead of Car clearly signals that a missing
value is permitted there. Conversely, always using the type Car and possibly assigning a null
reference to a variable of that type implies you don't have any help, other than your knowledge
of the business model, to understand whether the null belongs to the valid domain of that given
variable or not.
With this in mind, you can rework the original model from listing 10.1 , using the Optional class
as follows.
Listing 10.4. Redefining the Person / Car / Insurance data model using
Optional
Note how the use of the Optional class enriches the semantics of your model. The fact that a
person references an Optional<Car>, and a car an Optional<Insurance>, makes it explicit in the
domain that a person might or might not own a car, and that car might or might not be insured.
At the same time, the fact that the name of the insurance company is declared of type String
instead of Optional<String> makes it evident that it's mandatory for an insurance company to
have a name. This way you know for certain whether you'll get a NullPointerException when
dereferencing the name of an insurance company; you don't have to add a null check because
doing so will just hide the problem instead of fixing it. An insurance company must have a name,
so if you find one without, you'll have to work out what's wrong in your data instead of adding a
piece of code covering up this circumstance. Using optionals consistently disambiguates beyond
any doubt the case of a value that can be structurally missing from the case of a value that's
absent only because of a bug in your algorithm or a problem in your data. It's important to note
that the intention of the Optional class is not to replace every single null reference. Instead, its
purpose is to help you design more-comprehensible APIs so that by just reading the signature of
 
Search WWH ::




Custom Search