Objective
Before encountering the hidden bug brought after using optional, it is now emphasized to record bad usage and prevent mistakes.
Optional cannot be serialized and cannot be used as a field for a Class (field)
This is particularly important in that the classes are purely. If Pojo is the original type, you should not use optional as field if it is a domain object.
Optional cannot be used as a method parameter
Another case where optional is not appropriate is to use the type as a parameter to a method or constructor, which causes unnecessary code complications.
newUser("[email protected]""1234", Optional.empty());
Conversely, it is much more convenient to use method overloading to handle non-mandatory parameters.
Optional and steam combinations are more beneficial
Cascading calls are dangerous and can easily produce null pointers. Like what
String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();
In traditional practice,
ifnull) { Address address = user.getAddress(); ifnull) { Country country = address.getCountry(); ifnull) { String isocode = country.getIsocode(); ifnull) { isocode = isocode.toUpperCase(); } } }}
Using optional, you can streamline your code and reduce complexity:
String result = Optional.ofNullable(user) .flatMap(User::getAddress) .flatMap(Address::getCountry) .map(Country::getIsocode) .orElse("default");
Summarize
The optional class is the most useful use case for us that is used in combination with stream or other methods that return a optional value that can build a fluent API. If only as empty, then do not use optional, directly to the null is good.
For example, an example of a optional object using stream:
@Testpublic void whenGetStream_thenOk() { User user = new User("[email protected]", "1234"); List<String> emails = Optional.ofNullable(user) .stream() .filter(u -> u.getEmail() != null && u.getEmail().contains("@")) .map( u -> u.getEmail()) .collect(Collectors.toList()); assertTrue(emails.size() == 1); assertEquals(emails.get(0), user.getEmail());}
Reference
Original link: https://stackify.com/optional-java/
About
Eugen is a software engineer with great enthusiasm for spring, REST API, security, and education. He is also the founder of Baeldung (Twitter account @baeldung).
Optional usage considerations in Java