DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Optional isPresent() Is Bad for You

Optional isPresent() Is Bad for You

Learn about the benefits and drawbacks Optional objects can bring and how to use them to properly refactor your code. Hint: Don't use them with isPresent().

Mateusz Winnicki user avatar by
Mateusz Winnicki
·
Oct. 01, 16 · Tutorial
Like (52)
Save
Tweet
Share
157.70K Views

Join the DZone community and get the full member experience.

Join For Free

Before Java 8, if we wanted to check whether something is null, we had to write crappy null checks. Today, we have better alternatives.

Consider a situation when we have a method that returns a logo from Person. Unfortunately, we don’t know if our person exists (in this situation, we want the default logo), so we have to check if Person is not null:

public Logo getLogoOrReturnDefault(Person person) {
    if(person != null) {
        return person.getLogo();
    }
    return new DefaultLogo();
}

Okay, we did a check, and we are happy that our code is not failing because of NPE. We can also bypass this by using a list of Persons instead of single object and do a foreach. We can also check if the list is empty before doing anything. Another solution is that we can refactor our code to use the NullObject pattern. Finally, we can stick to the “fail fast” rule — no checks and NPE when Person is null. BUT we have Java 8 in our project, so there is a special thing called Optional. Okay, wonderful, we take that object and refactor our code to Java 8 standards:

public Logo getLogoOrReturnDefault(Person person) {
    Optional<Person> optionalPerson = Optional.ofNullable(person);
    if(optionalPerson.isPresent()) {
        return optionalPerson.get().getLogo();
    }
    return new DefaultLogo();
}

Nice, no null in our code. It is better than before? No. It is easier to read? Not really. Can we do it better? Yes!
I have seen this wannabe-refactor many times. Before we create a better solution, I want to share another example of “nice” usage of Optional.

final Optional<Person> bigPerson = members.stream()
    .filter(member -> member.getLevel() > 10)
    .findFirst();
if (bigPerson.isPresent()) {
    //many lines of code here
    return something;
} else {
    return another;
}

Of course, I know why someone wrote this ugly creature. They simply do not know how Optional objects are powerful and how to use that to improve the readability of code. In my opinion, Optional's best property is not hiding nulls or telling that our method can return something or not. The biggest feature that Optional brings us is transforming. We do not simply check if an Optional object is empty or not. We can transform it to what we want (as many times as we want) in a few lines and provide alternative solutions when one of the steps of transforming is not returning existing results. So, instead of checking wheter our person exists with isPresent(), we can do this:

public Logo getLogoOrReturnDefault(Person person) {
    return Optional.ofNullable(person)
        .map(p -> p.getLogo())
        .orElse(new DefaultLogo());
}

And a second example:

final Optional<Person> highLevelPerson = members.stream()
    .filter(member -> member.getLevel() > 10)
    .findFirst()
    .map(member -> privateMethodFromManyLinesOfCode(member))
    .orElse(another);

This is a very simple example, but we can do more map operations or add many filter operations. We can do whatever we want without a single if statement or null. I suppose that all if statements can be refactored to Optional object with some operations on it. Am I wrong?

Remember one thing — if you're using Optional and you wrote isPresent() or get() you are wrong and can do it better.

Object (computer science) Java (programming language) Filter (software) Property (programming) Logo (programming language)

Published at DZone with permission of Mateusz Winnicki, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Visual Network Mapping Your K8s Clusters To Assess Performance
  • Top Five Tools for AI-based Test Automation
  • A Real-Time Supply Chain Control Tower Powered by Kafka
  • The Quest for REST

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: