November 25, 202610 minutes
Twelve bikes, thirteen riders, and every field private. Learn what encapsulation really protects: the object's promise, and the decisions likely to change.
Tuesday’s spin class has twelve bikes. Thirteen riders turn up, and every one of them has a booking. The app says there are minus two spots left. But twelve bikes minus thirteen riders is minus one, so even the count is wrong. Nobody touched the code of the spin class itself. So who broke it? The answer is encapsulation, and it’s about much more than private fields.
Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.
Two numbers on one screen disagree with each other and with reality: thirteen riders for twelve
bikes, and a spots-left count of −2 when 12 − 13 is −1. The SpinClass code didn’t change. Keep
the question in mind: who broke it?
Think of a wristwatch. You set it with one knob, the crown. Turn it, and both hands move together. Inside, a set of gears (watchmakers call it the motion work) moves the hour hand one twelfth as far as the minute hand, so the two hands always agree.
That’s a promise the watch keeps for you. In code, a promise like that is called an invariant: a rule about an object’s state that is always true.
And the inside can change. Spring or quartz crystal, you set the watch the same way. The crown and the face are the interface. The movement inside is the implementation.
Here’s the obvious first version. The spin class has a set of riders and a count of spots left, both public.
public class SpinClass {
public Set<String> riders = new HashSet<>();
public int spotsLeft = 12;
}The front desk app books a rider. It checks for a free spot and a repeated name, adds the name, and counts the spot down.
// FrontDeskApp
if (spin.spotsLeft > 0 && !spin.riders.contains(name)) {
spin.riders.add(name);
spin.spotsLeft--;
}It’s short, it’s clear, and it works, as long as every caller is this careful. With one careful caller, this is honest code.
Then another team writes the phone app. Their booking code is two lines, and it skips the check.
// PhoneApp
spin.riders.add(name);
spin.spotsLeft--;The class has one spot left when Sam taps book twice. The set ignores the second Sam, but the count goes down twice. Then Maya books, and nothing stops her.
| Step | riders | spotsLeft | 12 − riders |
|---|---|---|---|
| start | 11 | 1 | 1 |
| Sam taps book | 12 | 0 | 0 |
| Sam taps book again (set ignores it) | 12 | −1 | 0 |
| Maya books a full class | 13 | −2 | −1 |
Thirteen riders, minus two spots: the two fields no longer agree. So who broke it? Both apps did, each with its own copy of the rule. It lives in every caller, so every caller can get it wrong. The promise has no owner.
It’s a watch with the back off. Anyone can push one hand, and the hands stop agreeing.
The textbook fix is private fields, with a getter and a setter for each one. Let’s try it.
public class SpinClass {
private Set<String> riders = new HashSet<>();
private int spotsLeft = 12;
public Set<String> getRiders() { return riders; }
public int getSpotsLeft() { return spotsLeft; }
public void setSpotsLeft(int n) { spotsLeft = n; }
}Here’s the phone app now. It gets the set and adds to it. It gets the count, and sets it one lower.
// PhoneApp
spin.getRiders().add(name);
spin.setSpotsLeft(spin.getSpotsLeft() - 1);That’s the same bug with longer names. The getter hands out the real set, and the setter takes any number at all, including −2. A setter for each field is a knob for each hand.
Private is the lock, not the rule.
This is the most common misconception about encapsulation: that it means “make the fields private and generate accessors”. The fields moved; the rule didn’t.
So flip it around. Callers shouldn’t change the fields at all. They ask the class to book a rider, and the class keeps its own rule.
Martin Fowler puts it well (paraphrased): encapsulation is less about hiding data, and more about hiding design decisions, especially the ones likely to change. He suggests asking “what piece of variability are you hiding, and why?” rather than “am I exposing data?”
In the watch, the crown is that one door. You never touch the gears, and the watch never shows a time that can’t exist. So encapsulation has two jobs:
Guard the promise. Hide the decision.
Here’s the class. The fields are private, and there’s no spots left field any more.
public class SpinClass {
private final int bikes;
private final Set<String> riders = new HashSet<>();
public SpinClass(int bikes) { this.bikes = bikes; }
public boolean book(String name) {
if (riders.size() == bikes) return false;
return riders.add(name);
}
public int spotsLeft() { return bikes - riders.size(); }
public Set<String> riders() { return Set.copyOf(riders); }
}book checks both rules in one place. A full class or a repeated name returns false, and nothing
changes. (HashSet.add returns false for a name that’s already there.)spotsLeft() is worked out from the riders, every time. A number you don’t store can’t
disagree.riders() hands out a copy that nobody can change: Set.copyOf returns an unmodifiable set, so
the real set never leaves the class.Both apps shrink to the same three lines. Ask to book, and show the answer.
// FrontDeskApp and PhoneApp
if (!spin.book(name)) {
screen.say("Sorry, no spot for " + name);
}Now Sam’s second tap returns false, and Maya gets a polite no. The watch has its back on.
Now the second job. In the early seventies, David Parnas wrote about how to split a system into modules (“On the Criteria To Be Used in Decomposing Systems into Modules”, 1972). His advice was to list the decisions most likely to change, and give each one to a single module that hides it. He called it information hiding.
Here’s one. The instructor wants riders in the order they booked, so the set becomes a list. A
list allows repeats, so book now checks for the name itself. riders() keeps its old signature.
That’s the whole change.
private final List<String> riders = new ArrayList<>(); // was a HashSet
public boolean book(String name) {
if (riders.size() == bikes || riders.contains(name)) return false;
return riders.add(name);
}
public Set<String> riders() { return Set.copyOf(riders); } // unchanged
public List<String> inBookingOrder() { return List.copyOf(riders); }The desk app, the phone app and their tests compile untouched. With a public set, every caller would now let repeats in, quietly: they relied on the set to ignore them.
The JDK does this too. EnumSet has no public constructors, only static factories, and they pick
one of two hidden classes depending on the size of your enum: RegularEnumSet (backed by a single
long) for 64 or fewer constants, JumboEnumSet otherwise. You never see which (Joshua Bloch,
Effective Java, Item 1).
People often use encapsulation and information hiding as one word. They’re related, but not the same:
| Term | What it is |
|---|---|
| Encapsulation | bundling data with the methods that guard it: the tool |
| Information hiding | hiding each decision likely to change behind a stable interface: the reason |
private | the access modifier that enforces it: the lock |
Bloch’s rule of thumb (Effective Java, Item 15): make each class or member as inaccessible as possible.
There’s a quick test for all of this, called Tell, Don’t Ask. It’s linked most with Andy Hunt and Dave Thomas, the Pragmatic Programmers.
Asking reads the object’s state, decides outside it, and then acts. That’s the rule, copied into the caller:
// asking: the rule, copied into the caller
if (spin.spotsLeft() > 0 && !spin.riders().contains(name)) {
spin.book(name);
}Telling hands over the whole job, and the object decides with its own data: that’s the
if (!spin.book(name)) caller above. A method that keeps reaching into another object’s data has a
name:
Feature Envy.
Fowler adds a caution: queries are fine. Showing spots left on a screen is no crime. Deciding with it outside the class is the trap. (He warns against becoming a “getter eradicator” who removes every query method.)
LocalDateYou already use a well guarded class: java.time.LocalDate. Try to make February the thirtieth,
and it throws.
LocalDate end = LocalDate.of(2026, 2, 28);
LocalDate next = end.plusDays(1); // 2026-03-01
// end is still 2026-02-28
LocalDate.of(2026, 2, 30); // DateTimeExceptionThere are no setters at all. Add one day to the last day of February, and you get a new date: the first of March. The original never changes. It’s checked once, when it’s made, and stays valid for its whole life: the javadoc calls it an immutable date-time object.
That’s our spin class idea, taken all the way. One door in, checked at the door, and no way around it. (If you liked this, Primitive Obsession shows the same move for values like distances and durations.)
So should every field hide behind methods? No. Some data has no promise to keep. A ruler has no mechanism: its markings are the data.
The card the phone shows for a class is a title, a start time and a number. Nothing has to agree,
so a record says it honestly. Java records (final since Java 16) are “transparent carriers for
immutable data”: the compiler writes the boring parts for you, the final fields, the accessors,
equals, hashCode and toString.
public record ClassCard(String title, LocalTime start, int spotsLeft) {
public ClassCard {
if (spotsLeft < 0) throw new IllegalArgumentException("spotsLeft < 0");
}
}And if one value does have a rule, a compact constructor checks it once, when the card is made. No card can say minus two.
Joshua Bloch draws the line in Effective Java (Item 16, paraphrased): public classes shouldn’t expose mutable fields; inside a package, or in a private nested class, plain fields can be fine.
Two cautions. A record holding a mutable List still hands that list out, so copy it
(List.copyOf) in the compact constructor. And records are honest about being data; classes are
honest about keeping promises. The trouble starts when a class with a promise acts like a record,
which is exactly where we started.
Checklist:
Guard the promise. Hide the decision.
Related lessons: Polymorphism (the promise every implementation keeps), Feature Envy, Data Clumps, Large Class.
java.time.LocalDate.