Why this matters
- These two are routinely given as each other's definitions, and a precise answer is a quick signal of real understanding.
- Weak encapsulation is the root cause of the bug where an object is valid when you create it and invalid an hour later.
- Choosing the right abstraction determines how much of your codebase has to change when a requirement does.
Encapsulation: the object guards its own state
The mechanism is simple — private fields, public methods — but the point is the invariant, the rule that must always hold.
The invariant is "balance is never negative". Because balance is private and there is no setter,
that rule holds for the entire life of the object. No caller can break it, even by mistake.
The getter-and-setter habit
Generating a getter and setter for every field is the most common misunderstanding of encapsulation. The question to ask is what operation the caller actually wants.
| Aspect | Field-oriented API | Operation-oriented API |
|---|---|---|
| Shape | getStatus() / setStatus() | approve() / reject() |
| Where rules live | Scattered across every caller | Inside the class, once |
| Invalid states | Reachable by any caller | Unreachable |
| Reading the code | What does setting status to 2 mean? | Obvious from the name |
| Changing the rule | Find every call site | Edit one method |
Shape
Field-oriented APIgetStatus() / setStatus()Operation-oriented APIapprove() / reject()Where rules live
Field-oriented APIScattered across every callerOperation-oriented APIInside the class, onceInvalid states
Field-oriented APIReachable by any callerOperation-oriented APIUnreachableReading the code
Field-oriented APIWhat does setting status to 2 mean?Operation-oriented APIObvious from the nameChanging the rule
Field-oriented APIFind every call siteOperation-oriented APIEdit one method
Expose what callers want to do, not the fields that happen to implement it.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- Defensive copying
- Abstraction: hiding complexity, not data
- The two side by side
- Package-private as a design tool
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.