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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • What Is Ant, Really?
  • Writing DTOs With Java8, Lombok, and Java14+
  • Filtering Java Collections via Annotation-Driven Introspection
  • Redefining Java Object Equality

Trending

  • Supercharging AI Agents with Azure Context: A Hands-On Guide to Azure MCP
  • How to Format Articles for DZone
  • PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look
  • Frame Buffer Hashing for Visual Regression on Embedded Devices

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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().

By 
Mateusz Winnicki
·
Oct. 01, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
163.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • What Is Ant, Really?
  • Writing DTOs With Java8, Lombok, and Java14+
  • Filtering Java Collections via Annotation-Driven Introspection
  • Redefining Java Object Equality

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook