Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining Optional.orElseThrow

I have a piece of code like this:

return getObject()
    .map(obj -> obj.getNullableField())
    .orElseThrow(() -> new IllegalStateException("Object not found!"));

At the moment I'm throwing an exception when the given Object is not present.

Now I need to also check if the nullableField of Object is present.

One obvious solution could be something like this:

var fieldVal = getObject()
    .map(obj -> obj.getNullableField())
    .orElseThrow(() -> new IllegalStateException("Object not found!"));

  return Optional.ofNullable(fieldVal)
     .orElseThrow(() -> new IllegalStateException("Field is not present"));

But I'd like to implement this in the same functional chain...

What am I missing?

like image 866
davioooh Avatar asked Feb 26 '19 15:02

davioooh


2 Answers

It could be implemented within the same chain directly, you would get different exception thrown. Now, it's less readable than your first solution of course, so you have a trade-off.

return getObject().map(obj -> Optional.ofNullable(obj.getNullableField())
                                      .orElseThrow(() -> new IllegalStateException("Field is not present")))
                  .orElseThrow(() -> new IllegalStateException("Object not found!"));
like image 54
Yassin Hajaj Avatar answered Nov 18 '22 02:11

Yassin Hajaj


Rather than nesting, I would suggest a simple sequence to solve that as:

var value = getObject()
        .orElseThrow(() -> new IllegalStateException("Object not found!"));

return Optional.of(value) // ensured value check already
        .map(CustomObject::getNullableField) // takes care ofNullable
        .orElseThrow(() -> new IllegalStateException("Field is not present"));
like image 42
Naman Avatar answered Nov 18 '22 04:11

Naman