Card 01/ 08

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.

java
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.

What changes when a field becomes private
Compared onPublic fieldPrivate field with methods
Places that can change itAnywhere in the programThis class
Places a rule must be writtenEvery one of themOne
Changing how it is storedBreaks every callerInvisible 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.