Encapsulation
Data hiding with getters/setters and invariant protection.
16 minLevel 8 of 20
Data hiding
Encapsulation hides representation and exposes a safe API. Callers should not be able to put an object into an invalid state.
Open the Encapsulation Lab to toggle public/private and watch illegal access get blocked.
Protect invariants
class Temperature {
constructor(private celsius: number) {
if (celsius < -273.15) throw new Error("below absolute zero");
}
getC() { return this.celsius; }
setC(v: number) {
if (v < -273.15) throw new Error("invalid");
this.celsius = v;
}
}
const t = new Temperature(20);
t.setC(25);
console.log(t.getC());Getters and setters
Getters/setters are controlled doors. Prefer methods that express intent (withdraw) over raw field writes (balance = -1).
Intent-revealing API
class Wallet {
constructor(private cents: number) {}
get balance() { return this.cents / 100; }
withdraw(dollars: number) {
const c = Math.round(dollars * 100);
if (c > this.cents) throw new Error("insufficient");
this.cents -= c;
}
}
const w = new Wallet(5000);
w.withdraw(12.5);
console.log(w.balance);Encapsulation in Nest modules
A Nest module encapsulates providers. Export only what other modules need — the module boundary is encapsulation at architecture scale.
Module boundary (conceptual)
// users.module exports UsersService, not UsersRepository
class UsersRepository { find() { return ["Ada"]; } }
class UsersService {
constructor(private repo: UsersRepository) {}
list() { return this.repo.find(); }
}
// Outside modules depend on UsersService only:
console.log(new UsersService(new UsersRepository()).list());Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice