HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaMinor

Use optional to check Null pointer exception

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkexceptionnullpointeroptionaluse

Problem

I currently have something like this:

Price price = new Price();
ActualValue actualValue = new ActualValue();
actualValue.setValue(price.getPreviousPrice().getRegion().getValue());


I want to make sure when calling getRegion() and getValue(), no NPE is thrown, trying to make it write in one line so I thought about using Optional

Currently what I have is this:

Optional.of(price)
            .flatMap(d -> Optional.ofNullable(d.getPreviousPrice())
            .flatMap(p -> Optional.ofNullable(p.getRegion())
                    .flatMap(m -> Optional.ofNullable(m.getValue()))))
            .ifPresent(v -> actualValue.setValue(v));


Looks ugly, how can I improve?

Solution

Optional.map produces a cleaner code. It's similar to flatMap except the function inside doesn't need to know about Optional. Also passing method references makes things a little bit shorter.

Optional.of(price)
        .map(Price::getPreviousPrice)
        .map(Price::getRegion)
        .map(Region::getValue)
        .ifPresent(ActualValue::setValue);

Code Snippets

Optional.of(price)
        .map(Price::getPreviousPrice)
        .map(Price::getRegion)
        .map(Region::getValue)
        .ifPresent(ActualValue::setValue);

Context

StackExchange Code Review Q#153949, answer score: 7

Revisions (0)

No revisions yet.