3
\$\begingroup\$

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?

200_success
146k22 gold badges190 silver badges478 bronze badges
asked Jan 30, 2017 at 2:54
\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

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);
answered Jan 30, 2017 at 3:45
\$\endgroup\$
0
0
\$\begingroup\$

My advice is to make rare use of the Optional-construct. It may make the code look "cleaner" and surly "shorter" but it brings a false sense of safety. BTW less code is no metric to follow.

I would come from the other side and ask questions like:

  1. Do I violate the law of demeter with "price.getPreviousPrice().getRegion().getValue()"?
  2. Why should a previous price have no region where it is valid?

You should have a look at your design. These new constructs may have their applications. But most of the time I see them in usage they hide design flaws. Semantical problems where obfuscated by language mechanisms.

answered Feb 1, 2017 at 21:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.