Java Reference
In-Depth Information
16.1.4. Optional
The Java 8 library provides the class Optional<T>, which allows your code to specify that a
value is either a proper value of type T or is a missing value returned by the static method
Optional.empty. This is great for program comprehension and documentation; it provides a data
type with an explicit missing value—instead of the previous error-prone use of the null pointer
to indicate missing values, which we could never be sure was a planned missing value or an
accidental null resulting from an earlier erroneous computation.
As chapter 10 discusses, if Optional<T> is used consistently, then programs should never
produce NullPointerExceptions. Again you could see this as a one-off, unrelated to the rest of
Java 8, and ask, “How does changing from one form of missing value to another help me write
programs?” Closer inspection shows that the class Optional<T> provides map, filter, and
ifPresent. These have similar behavior to corresponding methods in the Streams class and can
be used to chain computations, again in functional style, with the tests for missing value done
by the library instead of user code. This internal testing versus external testing choice is directly
analogous to how the Streams library does internal iteration versus external iteration in user
code.
Our final topic of this section concerns not functional-style programming but instead Java 8
support for upward-compatible library extensions driven by software-engineering desires.
16.1.5. Default methods
There are other additions to Java 8, none of which particularly affect the expressiveness of any
individual program. But one thing that is helpful for library designers is the addition to allow
default methods to be added to an interface. Prior to Java 8, interfaces defined method
signatures; now they can also provide default implementations for methods that the interface
designer suspects not all clients will want to provide explicitly.
This is a great new tool for library designers, because it provides them with the ability to
augment an interface with a new operation, without having to require all clients (classes
implementing this interface) to add code to define this method. Therefore, default methods are
also relevant to users of libraries because they shield them from future interface changes.
Chapter 9 explains this in more detail.
So far we've summarized the concepts of Java 8. We now turn to the thornier subject of what
future enhancements and great new features may be in Java's pipeline beyond Java 8.
 
Search WWH ::




Custom Search