Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite service request using optionals

I want to rewrite the code below using Optionals ( I do not control jpaConnector ):

public boolean deleteLockStatus() {

    IMdss service = jpaConnector.getMdssService();
    if ( service == null ) {
        return false;
    }

    ServiceResponse response = null;
    try {
        response = service.deleteLockStatus();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if ( response == null ) {
        return false;
    }
    if ( response.isError() ) {
        return false;
    }
    return true;
}

I have achievied this so far:

public boolean deleteLockStatus() {

    Optional<IMdss> service = Optional.ofNullable(jpaConnector.getMdssService());

    if (!service.isPresent()) { return false; }


    Optional<ServiceResponse> response = Optional.empty();
    try {
        response = Optional.ofNullable(service.get().deleteLockStatus());
        if ( response.isPresent() == false || response.get().isError() ) {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

Is there a better and more native java 8 way? Thank you!!!

like image 447
Shakka Avatar asked Mar 13 '26 18:03

Shakka


1 Answers

We start with an Optional<Service>, flat map that to an Optional<ServiceResponse> (using the regular map function would give us Optional<Optional<ServiceResponse>>), then map that to an Optional<Boolean>.

The Optional<Boolean> represents success or failure of the response. If we don't have a value here, an exception was thrown so we return false with orElse(false).

It's a shame about the checked exception and having to print the stack trace, or else it could be a lot more concise.

public boolean deleteLockStatus() {
    return Optional.ofNullable(jpaConnector.getMdssService())
        .flatMap(service -> {
            try {
                return Optional.ofNullable(service.deleteLockStatus());
            }
            catch(Exception e) {
                e.printStackTrace();
                return Optional.empty();
            }
        })
        .map(ServiceResponse::isError)
        .orElse(false);
}

Side note: catching Exception is usually a bad idea. You should be as specific as possible. Consider using this syntax if there are multiple possible exceptions which may be thrown.


As mentioned in the comments by Federico, you can replace the flatMap with this slight simplification if you don't mind using null. I would personally prefer the version above.

.map(service -> {
     try {
         return service.deleteLockStatus();
     }
     catch(Exception e) {
         e.printStackTrace();
         return null;
     }
 })
like image 79
Michael Avatar answered Mar 16 '26 09:03

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!