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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Legacy Code Refactoring: Tips, Steps, and Best Practices
  • Two Cool Java Frameworks You Probably Don’t Need
  • How To Build a Multi-Zone Java App in Days With Vaadin, YugabyteDB, and Heroku

Trending

  • Monolith: The Good, The Bad and The Ugly
  • How Can Developers Drive Innovation by Combining IoT and AI?
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  1. DZone
  2. Coding
  3. Java
  4. Java 8 Optional: How to Use it

Java 8 Optional: How to Use it

By 
Vasco Cavalheiro user avatar
Vasco Cavalheiro
·
May. 12, 14 · Interview
Likes (11)
Comment
Save
Tweet
Share
91.7K Views

Join the DZone community and get the full member experience.

Join For Free

Java 8 comes with a new Optional type, similar to what is available in other languages. This post will go over how this new type is meant to be used, namely what is it's main use case.

What is the Optional type?

Optional is a new container type that wraps a single value, if the value is available. So it's meant to convey the meaning that the value might be absent. Take for example this method:

public Optional<Customer> findCustomerWithSSN(String ssn) {
    ...
}

Returning Optional adds explicitly the possibility that there might not be a customer for that given social security number.

This means that the caller of the method is explicitly forced by the type system to think about and deal with the possibility that there might not be a customer with that SSN.

The caller will have to to something like this:

Optional<Customer> optional = findCustomerWithSSN(ssn);

if (optional.isPresent()) {
    Customer customer = maybeCustomer.get();
    ... use customer ...
}
else {
    ... deal with absence case ...
}

Or if applicable, provide a default value:

Long value = findOptionalLong(ssn).orElse(0L);

This use of optional is somewhat similar to the more familiar case of throwing checked exceptions. By throwing a checked exception, we use the compiler to enforce callers of the API to somehow handle an exceptional case.

What is Optional trying to solve?

Optional is an attempt to reduce the number of null pointer exceptions in Java systems, by adding the possibility to build more expressive APIs that account for the possibility that sometimes return values are missing.

If Optional was there since the beginning, most libraries and applications would likely deal better with missing return values, reducing the number of null pointer exceptions and the overall number of bugs in general.

What is Optional not trying to solve

Optional is not meant to be a mechanism to avoid all types of null pointers. The mandatory input parameters of methods and constructors still have to be tested for example.

Like when using null, Optional does not help with conveying the meaning of an absent value. In a similar way that null can mean many different things (value not found, etc.), so can an absent Optional value.

The caller of the method will still have to check the javadoc of the method for understanding the meaning of the absent Optional, in order to deal with it properly.

Also in a similar way that a checked exception can be caught in an empty block, nothing prevents the caller of calling get() and moving on.

What is wrong with just returning null?

The problem is that the caller of the function might not have read the javadoc for the method, and forget about handling the null case.

This happens frequently and is one of the main causes of null pointer exceptions, although not the only one.

How should Optional be used then?

Optional should be used mostly as the return type of functions that might not return a value.

In the context of domain driver development, this means certain service, repository or utility methods such as the one shown above.

How should Optional NOT be used?

Optional is not meant to be used in these contexts, as it won't buy us anything:

  • in the domain model layer (not serializable)
  • in DTOs (same reason)
  • in input parameters of methods
  • in constructor parameters

How does Optional help with functional programming?

In chained function calls, Optional provides method ifPresent(), that allows to chain functions that might not return values:

findCustomerWithSSN(ssn).ifPresent(() -> System.out.println("customer exists!"));

Useful Links

This blog post from Oracle goes further into Optional and it's uses, comparing it with similar functionality in other languages - Tired of Null Pointer Exceptions

This cheat sheet provides a thorough overview of Optional - Optional in Java 8 Cheat Sheet

Java (programming language) IT

Opinions expressed by DZone contributors are their own.

Related

  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Legacy Code Refactoring: Tips, Steps, and Best Practices
  • Two Cool Java Frameworks You Probably Don’t Need
  • How To Build a Multi-Zone Java App in Days With Vaadin, YugabyteDB, and Heroku

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!