foundation
Encapsulation
Hide representation details behind methods or accessors so callers depend on stable behavior instead of mutable internals.
Encapsulation hides representation details behind a stable API so callers depend on behavior, not mutable internals. Private fields, getters with validation, and narrow public methods protect invariants—an `Account` cannot go negative if withdrawals go through `debit(amount)`.
In TypeScript, `private` is compile-time only unless you use `#field` runtime privacy.
On interviews: refactor public fields to methods preserving invariants and explain why law of Demeter follows from good encapsulation.
Common pitfalls: getters/setters that expose everything, anemic data bags with logic scattered outside, and "private" that is only convention in JS.
The trade-off is safety and evolvability versus direct field access convenience.
Checklist:
- Hide mutable state; expose operations.
- Enforce invariants at boundaries.
- Know compile-time vs runtime privacy in TS.