jeudi 14 janvier 2021

How to combine and optimize checks for optional's values if present

I have an Immutable class that holds 3 Optional values. I have written a method to validate if the values of them are present, when the optional properties are present. The class looks like the following. I'm wondering how I can refactor these to group them and reduce the number of lines/repetition.

public interface Employees {

Optional<Set<String>> names();

Optional<Set<Question>> applicationQuestions();

Optional<Set<Experience>> experienceData();

@Value.Check
default void validateAttributes() {
    names().ifPresent(names -> {
        if (names.stream().anyMatch(StringUtils::isBlank)) {
            throw new IllegalArgumentException("Names cannot be empty if present");
        }
    });
    applicationQuestions().ifPresent(applicationQuestions -> {
        if (applicationQuestions.isEmpty()) {
            throw new IllegalArgumentException("Application questions cannot be empty if present");
        }
    });
    experienceData().ifPresent(experienceData -> {
        if(experienceData.isEmpty()) {
            throw new IllegalArgumentException("Experience data cannot be empty if present");
        }
    });
}

static Employees.Builder builder() {
    return ImmutableEmployees.builder();
}
}

Any advice/suggestions to optimize this check and group them together would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire