Java 8 optional how to handle too many orelses

Let's look at an example without Lambdas:

@H_ 502_ 8@

@H_ 502_ 8@

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 is returned only if the user is not null ok(). Otherwise, status is returned bad(). Now use Lambdas (the service method returns optional < T >): @ h_ 502_ 8@

@H_ 502_ 8@

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 to status twice Bad () (in actual code, about 4-5) This is a return to status Bad () method@ H_ 502_ 8@

Solution

I can guess userservice:: get return. In this case, you'd better use flatmap:

@H_ 502_ 8@

@H_ 502_ 8@

CredentialService.get(id)
         .filter(Credentials::isActive)
            .flatMap(credentials -> UserService.get(credentials.getUserId())
            .map(Status::ok)
            .orElse(Status.bad())
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>