# EncapsulationTwelve 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.

{{< lesson-video youtube="Ei6Tg-gqbtE" title="Encapsulation" >}}

## Twelve bikes, thirteen riders

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?

## The watch

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

```mermaid {alt="The watch mapped onto code. The crown and face are the interface; the movement inside is the implementation; the hands always agreeing is the invariant; spring or quartz is a hidden design decision." caption="The watch, mapped onto the code."}
flowchart LR
  A["crown and face"] --> A2["interface"]
  B["movement inside"] --> B2["implementation"]
  C["the hands always agree"] --> C2["invariant"]
  D["spring or quartz"] --> D2["a hidden decision"]
  class A2 c1
  class C2 good
  class D2 muted
```

## The obvious version: public fields

Here's the obvious first version. The spin class has a set of riders and a count of spots left,
both public.

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

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

## Why it breaks: nobody owns the promise

Then another team writes the phone app. Their booking code is two lines, and it skips the check.

```java
// 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.**

```mermaid {alt="Both the front desk app and the phone app write directly to the riders set and the spotsLeft count. The front desk app checks the rule; the phone app doesn't. Nobody owns the rule that the two fields agree." caption="The rule lives in every caller."}
flowchart LR
  D["FrontDeskApp<br/>checks the rule"] --> R["riders"]
  D --> S["spotsLeft"]
  P["PhoneApp<br/>no check"] --> R
  P --> S
  class P bad
  class R c5
  class S c4
```

It's a watch with the back off. Anyone can push one hand, and the hands stop agreeing.

## The textbook fix: private fields, same bug

The textbook fix is private fields, with a getter and a setter for each one. Let's try it.

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

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

## The key insight: the object keeps its own promise

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

## Building it: one door in

Here's the class. The fields are private, and there's no spots left field any more.

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

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

```mermaid {alt="Class diagram of the encapsulated SpinClass: private bikes and riders fields; public book(name) returning boolean, spotsLeft() computed from the riders, and riders() returning an unmodifiable copy. FrontDeskApp and PhoneApp both call book." caption="One door in."}
classDiagram
  class SpinClass {
    -int bikes
    -Set~String~ riders
    +book(String name) boolean
    +spotsLeft() int
    +riders() Set~String~
  }
  FrontDeskApp --> SpinClass : book(name)
  PhoneApp --> SpinClass : book(name)
```

## Hide the decision: information hiding

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.

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

```mermaid {alt="Before and after the storage change. With public fields, switching riders from a Set to a List changes every caller's behavior: repeats get in. With the encapsulated class, only SpinClass changes and both apps are untouched." caption="Hide what's likely to change, and the change stays in one class."}
flowchart LR
  subgraph PUB["public set"]
    direction TB
    P1["Set → List"] --> P2["FrontDeskApp"]
    P1 --> P3["PhoneApp: repeats get in"]
  end
  subgraph ENC["one door in"]
    direction TB
    E1["Set → List<br/>inside SpinClass"] --> E2["book() checks repeats"]
    E3["both apps untouched"]
  end
  PUB ~~~ ENC
  class P3 bad
  class E2,E3 good
```

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.

## Tell, don't ask

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:

```java
// 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](/code-smells/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.)

## A date that can't be wrong: `LocalDate`

You already use a well guarded class: `java.time.LocalDate`. Try to make February the thirtieth,
and it throws.

```java
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);             // DateTimeException
```

There 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](/code-smells/primitive-obsession/) shows the same
move for values like distances and durations.)

## When public data is fine

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

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

```mermaid {alt="Decision: does the data have a rule that ties its parts together or limits its values? No: a record or plain fields are honest. Yes, a rule on one value: a record with a compact constructor. Yes, a rule across several fields or over time: a class with private state and one door in." caption="Pick the guard the data needs."}
flowchart TD
  Q{"does the data have a rule?"} -->|no| R["record / plain fields"]
  Q -->|"one value"| C["record + compact constructor"]
  Q -->|"across fields or over time"| K["class with one door in"]
  class R,C good
  class K c1
```

## Recap

- Public fields leave the rule to every caller, and the callers drift apart.
- Getters and setters move the fields, not the rule: same bug, longer names.
- One door in: a method that checks first, then changes; compute what must agree; hand out copies.
- Hide the decisions likely to change, so a change stays in one class.
- When there's no promise to keep, a record is honest.

```mermaid {alt="Recap chain: find the promise, give it one door in, hide the decision, and use a record when there's no promise." caption="Guard the promise. Hide the decision."}
flowchart LR
  A["find the promise"] --> B["one door in"] --> C["hide the decision"] --> D["no promise: record"]
  class B c1
  class D good
```

Checklist:

- Can any caller put the object in a state that breaks its rule?
- Is the same check copied into more than one caller?
- Does a getter return a live collection or array?
- Is a stored value really derived from other fields?
- Which decision inside this class is most likely to change, and would callers notice?

> **Guard the promise. Hide the decision.**

Related lessons: [Polymorphism](/fundamentals/polymorphism/) (the promise every implementation
keeps), [Feature Envy](/code-smells/feature-envy/), [Data Clumps](/code-smells/data-clumps/),
[Large Class](/code-smells/large-class/).

## Further reading

- David L. Parnas, "On the Criteria To Be Used in Decomposing Systems into Modules", *Communications
  of the ACM* 15(12), 1972. [doi:10.1145/361598.361623](https://doi.org/10.1145/361598.361623)
- Martin Fowler, [GetterEradicator](https://martinfowler.com/bliki/GetterEradicator.html) and
  [TellDontAsk](https://martinfowler.com/bliki/TellDontAsk.html).
- Joshua Bloch, *Effective Java* (3rd ed.), Items 1, 15 and 16.
- [JEP 395: Records](https://openjdk.org/jeps/395);
  [`java.time.LocalDate`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/LocalDate.html).
