Course contentsShow
← Java
Lesson 343 of 2,8708. Classes and EncapsulationFree lesson

Validation Logic in Setters

Implementing argument validation in setters to maintain object invariants and throw IllegalArgumentException.

Validation Logic in Setters

What you'll learn: How to write setters that validate incoming data and reject invalid values to keep your objects in a valid state.

Why Validate in Setters?

When you expose setter methods, you're allowing external code to modify your object's state. Without validation, callers could set nonsensical or dangerous values—like a negative age, an empty name, or a percentage over 100. Validation logic in setters acts as a gatekeeper, ensuring only valid data gets stored in your private fields.

The Pattern: Check First, Assign Second

A setter with validation follows this structure:

public void setAge(int age) {
    if (age < 0 || age > 150) {
        throw new IllegalArgumentException("Age must be between 0 and 150");
    }
    this.age = age;
}

The flow:

  1. Check if the argument violates your object's rules (called invariants)
  2. If invalid, throw IllegalArgumentException with a clear message
  3. Only if valid, assign the value to the field

Real-World Example

public class BankAccount {
    private double balance;
    
    public void setBalance(double balance) {
        if (balance < 0) {
            throw new IllegalArgumentException("Balance cannot be negative");
        }
        this.balance = balance;
    }
}

Without this check, someone could set balance to -1000.0, creating an invalid account state.

Why IllegalArgumentException?

This specific exception signals "you gave me bad input." It's a runtime exception, meaning callers aren't forced to catch it—but they'll know immediately when they pass invalid data.

Key Takeaway: Always validate setter arguments to maintain object invariants; throw IllegalArgumentException when invalid data is passed to prevent your object from entering a broken state.