Card 01/ 08

ConceptDifficulty: Intermediate1 min

Encapsulation: Private Fields and the Methods That Guard Them

A balance goes negative, fourteen files assign to it, and finding the culprit takes two days.

Encapsulation means a class keeps its fields private, so only its own code can read or change them, and everything else goes through its methods. The methods can then enforce the class's rules, such as a balance never going negative, in one place instead of wherever the field is used.

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.