Card 01/ 08
All 8 cards
ConceptDifficulty: Intermediate1 min
Keeping a Field Where Only Its Owner Can Reach It
An account balance goes negative in production. Fourteen files assign to that field, and one of them does it without checking anything first. Finding which took two days.
The fix is not a better check in fourteen places. It is making thirteen of them impossible.
class Account {
private long pence;
void withdraw(long amount) {
if (amount > pence) {
throw new IllegalArgumentException("insufficient funds");
}
pence -= amount;
}
long balance() { return pence; }
}private means one thing exactly: the name pence may be written inside this class and nowhere else. Every route to that number now goes through a method, and every method can enforce whatever the class needs to be true.
| Compared on | Public field | Private field with methods |
|---|---|---|
| Places that can change it | Anywhere in the program | This class |
| Places a rule must be written | Every one of them | One |
| Changing how it is stored | Breaks every caller | Invisible outside the class |
So encapsulation is not about hiding things from people. It is about reducing the number of places that have to be right, which is the same reason a method exists at all.