Optional usage considerations in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.