Sub topic 8
Validating Constructor Arguments and Preserving Invariants
A constructor is the code that runs when you create an object. An object is a value created from a class, which defines its data and behavior. A constructor can check its arguments, the values passed to it, before storing them.
Validation is the process of checking whether a value is allowed. It matters because a bad value can make an object behave in unexpected ways.
An invariant is a rule that must remain true for an object. For example, a battery’s charge might need to stay between 0 and 100 percent. The constructor must establish that rule. Any later change must preserve it.
Check before storing
A field is a variable that belongs to an object. In the example below, the charge field stores a battery’s charge as a whole number.
A method is a named set of instructions. The setCharge method changes the field, while getCharge reads it. Both the constructor and setCharge call checkCharge before storing a value.
Save this code as Battery.java:
class Battery {
private int charge;
Battery(int initialCharge) {
checkCharge(initialCharge);
charge = initialCharge;
}
void setCharge(int newCharge) {
checkCharge(newCharge);
charge = newCharge;
}
int getCharge() {
return charge;
}
private void checkCharge(int value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException(
"Charge must be from 0 to 100"
);
}
}
public static void main(String[] args) {
Battery battery = new Battery(70);
battery.setCharge(40);
System.out.println("Charge: " + battery.getCharge());
try {
battery.setCharge(110);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
System.out.println("Charge after rejected change: "
+ battery.getCharge());
try {
new Battery(-1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}Compile and run it:
javac Battery.java
java BatteryThe output is:
Charge: 40
Charge must be from 0 to 100
Charge after rejected change: 40
Charge must be from 0 to 100Follow the checks
The check uses ||, which means “or.” A value is rejected if it is less than 0 or greater than 100. Both 0 and 100 are allowed.
When the value is invalid, throw raises an exception. An exception is a signal that something went wrong. Here, IllegalArgumentException signals that a value passed to the constructor or method is not allowed.
The try and catch parts let the program handle that exception and continue. The catch block prints the error message.
The first rejected value is 110. The check runs before the assignment to charge, so the battery still holds 40. The second rejected value is -1. The constructor throws an exception, so the caller does not receive a battery from that creation attempt.
Protect the rule after construction
The constructor alone cannot protect the invariant forever. A later method could still put a bad value into the field.
The keyword private keeps code outside Battery from directly changing charge. Changes must go through the class’s methods. The setCharge method checks its argument using the same rule as the constructor.
Code inside the class must also follow the rule. If you add another method that changes charge, make sure it checks the new value before storing it.
Exercise
A battery has a charge of 40. What happens when setCharge(-1) is called, and what is its charge afterward?
Show answer
The method throws an IllegalArgumentException. The charge remains 40 because the check happens before the assignment.
Exercise
Are 0 and 100 valid constructor arguments? Why?
Show answer
Yes. The check rejects values below 0 or above 100, so both boundary values are allowed.