Java Record Constructor Validation Example

1. Introduction

In this blog post, we will explore the concept of constructor validation in Java Records. Java Records, introduced in Java 16, are a way to create immutable data classes with minimal boilerplate. Constructor validation in records enhances their functionality by ensuring data integrity right at the object creation stage.

Definition

Java Records automatically generate equals(), hashCode(), and toString() methods, along with a canonical constructor. Constructor validation in records allows for checking and normalizing field values during object instantiation, ensuring the data conforms to specified constraints.

2. Program Steps

1. Define a Java Record with fields that require validation.

2. Implement a compact constructor for validation.

3. Instantiate the record with both valid and invalid data to test the validation logic.

3. Code Program

// Record with constructor validation
public record Account(String username, String email) {
    public Account {
        if (username == null || username.isBlank()) {
            throw new IllegalArgumentException("Username cannot be blank");
        }
        if (email == null || !email.matches(".+@.+\\..+")) {
            throw new IllegalArgumentException("Invalid email format");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            Account validAccount = new Account("user123", "user123@example.com");
            System.out.println("Created Account: " + validAccount);
        } catch (IllegalArgumentException e) {
            System.out.println("Validation error: " + e.getMessage());
        }

        try {
            Account invalidAccount = new Account("", "user");
            System.out.println("Created Account: " + invalidAccount);
        } catch (IllegalArgumentException e) {
            System.out.println("Validation error: " + e.getMessage());
        }
    }
}

Output:

Created Account: Account[username=user123, email=user123@example.com]
Validation error: Username cannot be blank
Validation error: Invalid email format

Explanation:

1. The Account record is defined with a compact constructor that includes validation logic for username and email.

2. If username is blank or email doesn't match a basic email pattern, an IllegalArgumentException is thrown.

3. In the main method, an attempt to create valid and invalid Account instances is made.

4. For valid data, an Account object is successfully created. For invalid data, exceptions are caught and appropriate error messages are printed.

5. This example demonstrates how constructor validation in Java Records can be used to enforce data consistency and business rules.


Comments