How do you keep a class's internal state valid when other code can read and write it directly?
You make the state private and you put every change behind a method that checks the values. Then the class is the only thing that can break the rule, and it checks before it does.
public class BankAccount {
private final String owner;
private double balance;
public BankAccount(String owner, double startingBalance) {
if (startingBalance < 0) {
throw new IllegalArgumentException("balance cannot be negative");
}
this.owner = owner;
this.balance = startingBalance;
}
public void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive");
}
if (amount > balance) {
throw new IllegalStateException("not enough money");
}
balance = balance - amount;
}
public double balance() {
return balance;
}
}
So the design has three parts and they all matter.
The first part is that the field is private. In Java there is no way for code outside the class to write to it directly, so there is no way for the class to be put into a bad state by accident. The only ways in are the constructor and the methods.
The second part is that every method checks before it changes. The withdraw method checks that the amount is positive and that there is enough money, and then it changes the balance. So the balance can never go below zero and it can never be changed by a negative deposit.
The third part is that the rules live in one place. If a new rule comes along, such as a limit of five withdrawals a day, then you change the withdraw method and every caller gets the new behaviour for free.
the change what happens to the other code
-------------------------- ------------------------------------
a new rule on withdrawals nothing, the callers are untouched
a new way to read the nothing, the writers are untouched
balance
a bug in the rule it is fixed in one place
And there is a detail that is worth knowing about. The class above gives back the balance with a method called balance() rather than a field called balance. The reason is that a getter gives you the chance to change what is given back later without changing the callers. If the balance were a public field then every caller would have to be edited when you decide to hide it.
And there is a second detail worth knowing about. The check in the constructor matters as much as the check in the methods, because a new account is the one place where the starting balance could be wrong. If you only check in the methods then a bad balance can still be created, and the object is broken from the start.
So the rule to remember is this. Private fields, checked methods, and the checks live next to the data.
The last question in this topic explains what encapsulation means and what it buys you.