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

javasnippet
55 lines
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("  Ada@Example.COM  ", "  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("lin@example.com", 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());
        }
    }
}

What the code does

Java Record Compact Constructor Validation keeps everything in the classes UserAccounts and Account and the functions Account, hasRole and main.

Repetition is confined to for (String role : roles) — the rest of the file is straight-line. A guard precedes the IllegalArgumentException: bad state stops the flow there instead of continuing.

Applying it

The main signature reads public record Account(String email, String displayName, List<String> roles)

Each run prints the 6 labeled blocks normalized email:, has admin:, has viewer:, default name:, default roles:, rejected: in source order.

Start the program and main runs Account and hasRole one after another.

Statements that matter

throw new IllegalArgumentException("email must have one local part and one domain: " + email);
throw new IllegalArgumentException("roles must not contain blank entries");
return roles.contains(role);

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
`IllegalArgumentException` is raised at the guard, so invalid state never reaches the main logic.
What does Java Record Compact Constructor Validation print when run?
Invoke the file as-is — the `normalized email:`, `has admin:`, `has viewer:` prefixes identify which step printed each line.