Java Record Compact Constructor Validation

Validate and normalize a Java record in its compact constructor, default missing display names, and defensively copy a role list.

JavaForm Validation

Code

snippet
import java.util.List;
import java.util.Objects;

public class UserAccounts {

    public record Account(String email, String displayName, List<String> roles) {
        public Account {
            Objects.requireNonNull(email, "email must not be null");
            email = email.trim().toLowerCase();
            int at = email.indexOf('@');
            if (at <= 0 || at == email.length() - 1 || email.indexOf('@', at + 1) >= 0) {
                throw new IllegalArgumentException("email must have one local part and one domain: " + email);
            }

            if (displayName == null || displayName.isBlank()) {
                displayName = email.substring(0, at);
            } else {
                displayName = displayName.trim();
            }

            if (roles == null) {
                roles = List.of("reader");
            } else {
                for (String role : roles) {
                    if (role == null || role.isBlank()) {
                        throw new IllegalArgumentException("roles must not contain blank entries");
                    }
                }
                roles = List.copyOf(roles);
            }
        }

        public boolean hasRole(String role) {
            return roles.contains(role);
        }
    }

    public static void main(String[] args) {
        Account account = new Account("  [email protected]  ", "  Ada Lovelace  ", List.of("admin", "editor"));
        System.out.println(account);
        System.out.println("normalized email: " + account.email());
        System.out.println("has admin: " + account.hasRole("admin"));
        System.out.println("has viewer: " + account.hasRole("viewer"));

        Account defaults = new Account("[email protected]", null, null);
        System.out.println("default name: " + defaults.displayName());
        System.out.println("default roles: " + defaults.roles());

        try {
            new Account("not-an-email", "Test", List.of());
        } catch (IllegalArgumentException error) {
            System.out.println("rejected: " + error.getMessage());
        }
    }
}