Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Idiomatic Optionals

DZone's Guide to

Idiomatic Optionals

Developers still struggle to use Optionals properly in Java. Here is a simple rule to follow in your code so you don't fall into the trap.

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

Java 8 was released over 20 months ago and Java 7 already reached the end of life, yet it’s not that hard to stumble upon new code that uses classes from Java 8 but looks like it was coded in a Java 7.The anti-pattern I’m talking about is most common when conditional logic needs to be applied to java.util.Optional and it looks like this:

public Optional<String> getClientNumber(String personalId) {
    Optional<Client> client = clientRepository.getByPersonalId(personalId);
    return client.isPresent() ? Optional.of(client.get().getNumber()) : Optional.empty();
}

while it should look like that:

public Optional<String> getClientNumber(String personalId) {
    return clientRepository.getByPersonalId(personalId)
            .map(Client::getNumber);
}

As a rule of thumb every time you use an if-else block or ternary operator to consume Optional’s value or produce an alternative one take a moment and check if it can be written in an idiomatic way.Most of the time it can and should be written in such way because it makes the code more readable.

The only case I came across that requires ternary operator is when you need to convert an Optional<T> to a Stream<T>, fortunately, that will be taken care of in Java 9.      

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:
java ,optional

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}