1

How can I convert the below legacy java code to use Optional :

if (outer != null
        && outer.getInnerMethod() != null
        && outer.getInnerMethod().isAllowed()) {
   Obj value = outer.getInnerMethod().getSomethingElse();
}

Using something like Optional.ofNullable took me till here -

Optional.ofNullable(Outer.getOuter)
        .map(Outer::getInnerMethod)
        .map(SomethingElse::isAllowed)
        .ifPresent(.. );

But ifPresent will not have access to the outer object. What would be the cleanest way to transform something like this ?

2
  • Its kind of a 6 line unit test candidate to see what will happen. Commented May 6, 2020 at 7:25
  • You are mapping to isAllowed(), which yields an Optional<Boolean>. You want to use filter instead. Commented May 6, 2020 at 7:33

3 Answers 3

2

Do this

Optional.ofNullable(Outer.getOuter)
        .filter(outer -> ::Objects.nonNull(outer.getInnerMethod()))
        .filter(SomethingElse::isAllowed)
        .map (.. ); //or whatever operation you want to do here
Sign up to request clarification or add additional context in comments.

Comments

1

Use filter instead of map. From the java doc

If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.

Optional<Obj> optional = Optional.ofNullable(Outer.getOuter)
    .map(Outer::getInnerMethod)
    .filter(SomethingElse::isAllowed)
    .map(SomethingElse::getSomethingElse);

Comments

1

Instead of using map to chech if it's allowed use filter(e -> e.isAllowed()) this will filter out anything that isn't allowed.

Comments

Your Answer

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.