Java Reference
In-Depth Information
function passed to the optional's flatMap method transforms the square contained in the
original optional into an optional containing a triangle. If this function was passed to the map
method, the result would be an optional containing another optional that, in turn, contains a
triangle, but the flatMap method flattens this two-level optional into a single optional containing
a triangle.
Finding a car's insurance company name with optionals
Now that you know the theory of the map and flatMap methods of Optional, let's put them into
practice. The ugly attempts we made in listings 10.2 and 10.3 can be rewritten using the
optional-based data model of listing 10.4 as follows.
Listing 10.5. Finding a car's insurance company name with Optional s
Comparing listing 10.5 with the two former attempts shows the advantages of using optionals
when dealing with potentially missing values. This time, you can obtain what you want with an
easily comprehensible statement—instead of increasing the code complexity with conditional
branches.
In implementation terms, first note that you modify the signature of the getCarInsuranceName
method from listings 10.2 and 10.3 , because we explicitly said there could also be a case where a
nonexistent Person is passed to this method, such as when that Person is retrieved from a
database using an identifier, and you want to model the possibility that no Person exists in your
data for the given identifier. You model this additional requirement, changing the type of the
method's argument from Person to Optional<Person>.
Once again this approach allows you to make explicit through the type system something that
otherwise would remain implicit in your knowledge of the domain model, namely, you should
never forget that the first purpose of a language, even a programming language, is
communication. Declaring a method to take an optional as an argument or to return an optional
as a result documents to your colleagues—and all future users of your method—that it can take
an empty value or that it might give an empty value as result.
 
Search WWH ::




Custom Search