CSE Roadmap

Core tier · about 2 hours · 7 parts

Part 4 of 7 · 2 min read

Accessors, not public fields

Fields are the inside. Methods are the API.

EJ Item 16 advises that public classes should offer methods for reading data, and should keep the fields themselves hidden. A class with public fields cannot change its representation without changing its API, cannot enforce rules, and cannot take any action when a field is read. EJ shows a Point with public x and y as the example to avoid, and the encapsulated version with private fields, getters, and setters for mutable classes.

A getter returns a field. A setter changes one. Do not add either by habit. A setter hands every caller the power to put the object into any state. If the class has rules, a setter can break them.

A made-up bank account shows the point:

class Account {
    private long balanceCents;

    Account(long openingCents) {
        if (openingCents < 0) throw new IllegalArgumentException("negative opening balance");
        this.balanceCents = openingCents;
    }

    long balance() { return balanceCents; }

    void deposit(long cents) {
        if (cents <= 0) throw new IllegalArgumentException("deposit must be positive");
        balanceCents += cents;
    }

    void withdraw(long cents) {
        if (cents <= 0 || cents > balanceCents) throw new IllegalArgumentException("bad withdrawal");
        balanceCents -= cents;
    }
}

There is no setBalance. The only ways to change the balance are deposit and withdraw, and each protects the rule that the balance is never negative. With a public field, any line of code anywhere could write acct.balanceCents = -5000.

A rule that always holds is an invariant. Here it is "balance is at least zero". The constructor and every method that changes state must keep the invariant true. That is the practical job of encapsulation.

Invariant

An invariant is a rule about an object's data that must be true every time a method finishes.

Example: a bank account balance is never below zero.

Check yourself: 1. Why does the account have no setBalance? 2. Where is the invariant checked? 3. What can a public field never do?