Sub topic 8
Validating Constructor Arguments and Preserving Invariants
Why validation matters
A constructor is the special part of a class that sets up a new object. It can receive an argument, which is a value supplied by the caller. For example, a bank account constructor might receive a starting balance.
Not every argument makes sense. If this kind of account cannot have a negative balance, a starting balance of -100 should be rejected.
Validation is the process of checking that a value follows the rules. A constructor can validate its arguments before it puts them into the object.
An object’s state is the information stored in its fields. An invariant is a rule that must remain true about that state. For our account, the invariant is:
- The balance is always zero or greater.
The constructor must establish this rule. Methods that change the balance must preserve it.
A working account
This example stores money as a whole number of cents. It uses an int, a Java type for whole numbers. Using cents lets the example avoid fractional values.
The account has these rules:
- A starting balance may be zero or positive.
- A deposit or withdrawal must be greater than zero.
- A withdrawal may not be greater than the balance.
- A deposit may not make the balance too large to fit in an
int.
The last rule matters because an int has a maximum value. Java does not automatically reject every calculation that goes past it.
Save this program as AccountDemo.java:
public class AccountDemo {
public static void main(String[] args) {
Account account = new Account(1200);
System.out.println("Balance: " + account.getBalanceCents() + " cents");
account.deposit(300);
System.out.println("After deposit: " + account.getBalanceCents() + " cents");
try {
account.withdraw(2000);
} catch (IllegalArgumentException e) {
System.out.println("Withdrawal rejected: " + e.getMessage());
}
System.out.println(
"Balance after rejection: " + account.getBalanceCents() + " cents"
);
account.withdraw(500);
System.out.println(
"After withdrawal: " + account.getBalanceCents() + " cents"
);
try {
new Account(-1);
} catch (IllegalArgumentException e) {
System.out.println("Account rejected: " + e.getMessage());
}
}
}
class Account {
private int balanceCents;
Account(int initialBalanceCents) {
if (initialBalanceCents < 0) {
throw new IllegalArgumentException(
"Initial balance must be nonnegative"
);
}
this.balanceCents = initialBalanceCents;
}
void deposit(int amountCents) {
if (amountCents <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
if (amountCents > Integer.MAX_VALUE - balanceCents) {
throw new IllegalArgumentException("Deposit would make balance too large");
}
balanceCents += amountCents;
}
void withdraw(int amountCents) {
if (amountCents <= 0) {
throw new IllegalArgumentException("Withdrawal must be positive");
}
if (amountCents > balanceCents) {
throw new IllegalArgumentException("Amount exceeds balance");
}
balanceCents -= amountCents;
}
int getBalanceCents() {
return balanceCents;
}
}From the folder containing the file, compile and run it:
javac AccountDemo.java
java AccountDemoThe program prints these lines, in order:
| Step | Output |
|---|---|
| Create an account | `Balance: 1200 cents` |
| Deposit 300 cents | `After deposit: 1500 cents` |
| Try to withdraw too much | `Withdrawal rejected: Amount exceeds balance` |
| Check the balance | `Balance after rejection: 1500 cents` |
| Withdraw 500 cents | `After withdrawal: 1000 cents` |
| Try a negative starting balance | `Account rejected: Initial balance must be nonnegative` |
How the constructor checks its argument
In Account(int initialBalanceCents), initialBalanceCents is a parameter: a named place for an argument received by the constructor.
When the program calls new Account(1200), the argument is 1200. The constructor checks whether that value is less than zero. It is not, so the constructor assigns it to the balanceCents field.
When the program calls new Account(-1), the check is true. The constructor stops before assigning the field and throws an exception.
An exception is a signal that interrupts the normal flow of a program. The throw statement sends that signal. IllegalArgumentException is a built-in Java exception used when an argument is not acceptable.
The try and catch parts in main handle that exception. The statements in try run first. If a matching exception is thrown, the catch block runs. The variable e refers to the exception, and e.getMessage() reads the message supplied when it was created.
For the failed call to new Account(-1), the new expression does not return an account. The program can continue because the exception is caught.
Protect the rule after construction
A valid starting balance is not enough. If a later method could set the balance to -500, the invariant would be broken.
The field balanceCents is private. This means code outside the Account class cannot directly change it. Instead, the class offers methods for depositing, withdrawing, and reading the balance.
Each method that changes the balance checks its input before making the change:
depositrejects zero and negative amounts.depositalso checks that the new balance will fit in anint.withdrawrejects zero and negative amounts.withdrawrejects amounts greater than the current balance.- Only after its checks pass does a method change the field.
This order matters. When withdraw(2000) is called on an account holding 1500 cents, the method rejects the request before subtracting anything. The next line confirms that the balance is still 1500 cents.
The method getBalanceCents returns the current balance. It does not change the field.
Preventing a balance that is too large
An int can hold values up to Integer.MAX_VALUE, which is 2,147,483,647. If an addition goes past that limit, the result can wrap around to a negative number. This is called integer overflow. It could break the account’s nonnegative-balance invariant.
The deposit method checks for this before adding:
amountCents > Integer.MAX_VALUE - balanceCents
The part on the right is the space left before the balance reaches the maximum. If the deposit is larger than that space, the method rejects it.
For example, suppose the balance is Integer.MAX_VALUE - 1:
- A deposit of
1is allowed. The balance reaches the maximum. - A deposit of
2is rejected. The balance stays the same.
Checking after adding would be too late: the addition might already have produced a wrapped result.
Choose and test the boundaries
A boundary is an edge between accepted and rejected values. Testing both sides of a boundary helps show whether a rule is correct.
| Request | Expected result |
|---|---|
| Start with `-1` cent | Reject the account |
| Start with `0` cents | Create the account |
| Deposit `0` cents | Reject the deposit |
| Withdraw the full balance, when it is positive | Allow it; the balance becomes zero |
| Withdraw one cent more than the balance | Reject it; leave the balance unchanged |
| Deposit enough to reach the maximum `int` | Allow it |
| Deposit more than the remaining space | Reject it; leave the balance unchanged |
Notice that zero is allowed as a balance but not as a deposit or withdrawal. Those are separate rules. A different class could choose different rules, but its constructor and methods should follow them consistently.
When you test a rejected change, check two things: the method rejects the request, and the old balance remains unchanged.
Other kinds of argument checks
Numbers are not the only values that may need validation. A string is text, such as an account holder’s name. If a constructor requires a name, it might reject an empty string.
It may also need to reject null, which means there is no object reference. Check for null before calling a method on the string. For example, a check for an empty name must not call name.isEmpty() until it knows that name is not null.
The rules depend on what the class promises. If a name may contain spaces but may not be empty, say so. If a name made only of spaces is also invalid, check for that separately.
Do not silently replace every invalid argument with a value that seems reasonable. For example, changing a negative starting balance to zero hides a caller’s mistake. Rejecting it makes the problem visible.
Common mistakes
- Checking only the constructor. Later methods can still break the invariant. Check every method that changes the relevant state.
- Changing a field before checking. A rejected request may leave unwanted changes behind. Perform all needed checks first.
- Forgetting the exact boundary. If zero is valid, use a check that rejects values below zero, not values below or equal to zero.
- Ignoring numeric limits. A positive deposit can still cause overflow. Check that the result will fit before adding.
- Writing a vague message. A message such as
Invalid valuegives less help thanDeposit must be positive.
The account example is designed for one operation at a time. If several parts of a program can change the same account at once, keeping the invariant safe needs additional care.
Practice
Exercise
Why does new Account(-1) not return an account, and what handles the problem in the example?
Show answer
The constructor rejects the negative argument by throwing IllegalArgumentException. The matching catch block handles it.
Exercise
An account holds 500 cents. What happens when withdraw(501) is called?
Show answer
The method throws IllegalArgumentException before changing the balance, so the balance remains 500 cents.
Exercise
An account balance is Integer.MAX_VALUE - 1. Why is a deposit of 1 allowed, but a deposit of 2 rejected?
Show answer
One cent fits in the remaining space. Two cents would exceed the largest value an int can hold.