delver delver - 24 days ago 12
Java Question

Java 8 Optional how to deal with too many orElses

Let's take a look at the example without lambdas:

Credentials credentials = CredentialService.get(id);
if (credentials != null && credentials.isActive()) {
User user = UserService.get(credentials.getUserId());
if (user != null)
return Status.ok(user);
}
return Status.bad();


As you can see,
Status.ok()
will be returned only if user isn't
null
. Otherwise,
Status.bad()
will be returned. Now with lambdas (Service's methods now returns
Optional<T>
):

return CredentialService.get(id)
.filter(Credentials::isActive)
.map(credentials -> UserService.get(credentials.getUserId())
.map(Status::ok)
.orElse(Status.bad())
).orElse(Status.bad());


Now I have to return
Status.bad()
two times (in real code, about 4-5). Is it a way to return
Status.bad()
once?

Answer

I can guess UserService::get return Optional in this case you better to use flatMap:

CredentialService.get(id)
         .filter(Credentials::isActive)
            .flatMap(credentials -> UserService.get(credentials.getUserId())
            .map(Status::ok)
            .orElse(Status.bad())
Comments