Lombok builder to check non null and not empty

user1692342 picture user1692342 · Jul 1, 2017 · Viewed 40.1k times · Source

I have a class with variables I don't want it to be null or empty. Is there a way to use Lombok builder to set the property? I can use @NonNull but I won't be able to verify if it is empty or not. Obviously the other option is to write my own builder which does all these checks. For example:

class Person {
    @NonNull
    private String firstName;
    @NonNull
    private String lastName;

    public static class PersonBuilder() {
        // .
        // .
        // .
        public Person build() {
            //do checks for empty etc and return object
        }
    }
}

Answer

Kedar Prabhu picture Kedar Prabhu · Sep 13, 2017

Maxim Kirilov's answer is incomplete. It doesn't check for blank/empty Strings.

I've faced the same issue before, and I realized that in addition to using @NonNull and @Builder from Lombok, overload the constructor with a private access modifier, where you can perform the validations. Something like this:

private Person(final String firstName, final String lastName) {
    if(StringUtils.isBlank(firstName)) {
        throw new IllegalArgumentException("First name can't be blank/empty/null"); 
    }
    if(StringUtils.isBlank(lastName)) {
        throw new IllegalArgumentException("Last name can't be blank/empty/null"); 
    }
    this.firstName = firstName;
    this.lastName = lastName;
}

Also, throwing IllegalArgumentException makes more sense (instead of NPE) when String has blank, empty or null values.