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?
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!"));
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With