How do you design getters and setters so that they protect invariants instead of just exposing the fields?
You make the methods do something useful rather than just moving a value from one place to another. A setter that only assigns is a public field with extra typing on it.
public class Main {
public static void main(String[] args) {
Account a = new Account("Ada", 100.0);
a.setBalance(250.0);
System.out.println(a.balance()); // 250.0
}
}
And here is a design where the methods protect something.
public class Account {
private final String owner;
private double balance;
public Account(String owner, double startingBalance) {
this.owner = owner;
this.balance = startingBalance;
}
public void setBalance(double value) {
if (value < 0) {
throw new IllegalArgumentException("balance cannot be negative");
}
this.balance = value;
}
public void setOwner(String value) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("owner is required");
}
this.owner = value;
}
public String owner() {
return owner;
}
public double balance() {
return balance;
}
}
So what makes a setter good? Here are the checks.
the question a good answer
--------------------------------------------- -------------------------
Does it reject a bad value? yes
Does it keep the other fields consistent? yes
Does it do something other than assign? sometimes
Could a caller set the field directly anyway? no, it is private
And the best setters do not exist at all. If a field can only be changed in one way then a method that does that one thing is better than a setter that lets the caller write anything.
// A weak design. The caller can set the balance to anything.
public void setBalance(double value) {
this.balance = value;
}
// A stronger design. Only the sensible changes are possible.
public void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive");
}
balance = balance + amount;
}
public void withdraw(double amount) {
if (amount > balance) {
throw new IllegalStateException("not enough money");
}
balance = balance - amount;
}
And there is a fourth kind of setter that is worth knowing about, and it is the one that fires an event. When you change the state of a thing, other parts of the program may need to know about it. So the setter can do the change and then tell the others, and that keeps the notification next to the change where it belongs.
And there is one thing that you should not do. You should not have a setter that changes two fields and then relies on the caller to call a second method to fix things up. That is a half-finished operation and the object is in a strange state in between. Either the operation is one method or it is two methods that are each complete on their own.
So the rule to remember is this. A setter should check something, and if it does not then it should not exist.
The last question in this topic is about when getters and setters are not a good idea.