Search code examples
javaoption-typepredicatecode-cleanup

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


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();


Solution

  • 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"));
    }