Домой United States USA — software Understanding, Accepting, and Leveraging Optional in Java

Understanding, Accepting, and Leveraging Optional in Java

232
0
ПОДЕЛИТЬСЯ

Explore the nuances to creating, transforming, filtering, and method chaining with Java 8’s optionals and see what Java 9 has in store for the class.
Essentially, this is a wrapper class that contains an optional value, meaning it can either contain an object or it can simply be empty.
If we wanted to make sure we won’t hit the exception in this short example, we would need to do explicit checks for every value before accessing it:
As you can see, this can easily become cumbersome and hard to maintain.
To reiterate, an object of this type can contain a value or be empty. You can create an empty Optional by using the method with the same name:
In this example, the assertion is only executed if the user object is not null.
Next, let’s look at ways in which alternatives for empty values can be provided.
If the initial value of the object is not null, then the default value is ignored:
At first glance, it might seem as if the two methods have the same effect. However, this is not exactly the case. Let’s create some examples that highlight the similarities as well as the differences in behavior between the two.
First, let’s see how they behave when an object is empty:
The output of this code is:
Therefore, when the object is empty and the default object is returned instead, there is no difference in behavior.
The output this time is:
The structure above can be visually represented as a nested set:
The code above can be further reduced by using method references:
As a result, the code looks much cleaner than our early cumbersome, conditional-driven version.
If the object does contain a value, then the lambda expression is not executed:
This method can be useful if you want to perform an action using the value if one is present, or simply keep track of whether a value was defined or not:
Another situation when it’s not very helpful to use the type is as a parameter for methods or constructors. This would lead to code that is unnecessarily complicated:
Instead, it’s much easier to use method overloading to handle parameters that aren’t mandatory.
It’s also a well-designed and very natural addition to the new functional support added in Java 8.
Overall, this simple yet powerful class helps create code that’s, simply put, more readable and less error-prone than its procedural counterpart.

Continue reading...