Chapter 2 of 10All chapters
Chapter 2 of 10
Encapsulation
Hiding how, exposing what.
Why hide anything
If callers only use the methods, the internals can change freely. If they reach into the fields, every internal detail becomes a promise you cannot break.
- Expose behaviour rather than data: account.withdraw(50) not account.balance -= 50.
- A getter and setter for every field is encapsulation in name only.
Invariants
An invariant is something that must always be true, such as a balance never going negative. Encapsulation exists so one place can enforce it rather than every caller remembering.