lambda - Java 8 Optional how to deal with too many orElses -


let's take @ 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 can see, status.ok() returned if user isn't null. otherwise, status.bad() returned. lambdas (service's methods 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 have return status.bad() 2 times (in real code, 4-5). way return status.bad() once?

i can guess userservice::get return optional in case better use flatmap:

credentialservice.get(id)          .filter(credentials::isactive)             .flatmap(credentials -> userservice.get(credentials.getuserid())             .map(status::ok)             .orelse(status.bad()) 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -