Rewriting an if statement which throws an exception in a cleaner way

Csongi Nagy :

Let's suppose we have an if statement like this:

public A save(A a) {
    if (isValid.test(a)) {
        return aRepository.save(a);
    }
    throw new ANotValidException("A is not valid");
}

isValid is a Predicate and it may look like:

private Predicate<A> isValid = (a) -> (a != null);

What do you think? Can I make it cleaner somehow? I mean, for example using an Optional to reduce it in 1 line with an .orElseThrow();

Naman :

A more precise version using Optional and throwing a custom Exception shall be :

public A save(A a) throws ANotValidException { // throws the custom exception
    return Optional.ofNullable(a) // since your predicate is to check for not null 
                   .map(aRepository::save)
                   .orElseThrow(() -> new ANotValidException(a + "A is not valid"));
}

Guess you like

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