Is it a bad practice to throw exceptions in java 8 optional filters

user3495691 :

I wanted to leverage java 8 optional to validate values of the an object received (as a response). I'm curious to know, if it is a bad practice to do as below.

Optional.ofNullable(response)
.map(Response::getStatus)
.filter(status -> {
    if (status == Status.REJECTED)
        throw new RequestRejectedException("some exception");
    else if (status == Status.LOCKED)
        throw new ResourceLockedException("some other exception");
    return true;
})
.orElse(Status.UNAVAILABLE);

Wanted to know, if this is acceptable to write something like above or if there is a better way to do it, please suggest.

Andrew Tobilko :

No, it's not OK.

return true;

You don't filter anything, do you? It would be better to handle exceptions after the status is known.

final String status = Optional.ofNullable(response)
                              .map(Response::getStatus)
                              .orElse(Status.UNAVAILABLE);

if ("rejected".equals(status)) {
    throw new RequestRejectedException("some exception");
}

Judging from your comment, you seem to understand what Optional is for. No need to warn you it's an inappropriate usage.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309581&siteId=1