Java Reference
In-Depth Information
Indeed, we believe that many of those APIs would have been written differently if the Optional
class had been available at the time they were developed. For backward-compatibility reasons,
old Java APIs can't be changed to make proper use of optionals, but all is not lost. You can fix, or
at least work around, this issue by adding into your code small utility methods that allow you to
benefit from the power of optionals. You'll see how to do this with a couple of practical
examples.
10.4.1. Wrapping a potentially null value in an optional
An existing Java API almost always returns a null to signal the absence of the required value or
that the computation to obtain it failed for some reason. For instance, the get method of a Map
returns null as its value if it contains no mapping for the requested key. But for the reasons we
listed earlier, in most cases like this, you'd prefer that these methods could return an optional.
You can't modify the signature of these methods, but you can easily wrap the value they return
with an optional. Continuing with the Map example, and supposing you have a Map<String,
Object>, then accessing the value indexed by key with
Object value = map.get("key");
will return null if there's no value in the map associated with the String “key.” You can improve
this by wrapping in an optional the value returned by the map. You can do this in two ways:
either with an ugly if-then-else adding to code complexity or by using the method
Optional.ofNullable that we discussed earlier:
Optional<Object> value = Optional.ofNullable(map.get("key"));
You can use this method every time you want to safely transform a value that could be
potentially null into an optional.
10.4.2. Exceptions vs. Optional
Throwing an exception is another common alternative in the Java API to returning a null when,
for any reason, a value can't be provided. A typical example of this is the conversion of String
into an int, provided by the Integer.parseInt(String) static method. In this case, if the String
doesn't contain a parseable integer, this method throws a NumberFormatException. The net
effect is once again that the code signals an invalid argument in the case of a String not
representing an integer, the only difference being that this time you have to check it with a
try/catch block instead of using an if condition controlling whether a value is not null.
 
Search WWH ::




Custom Search