Hone

Lessons · TypeScript · private, protected, readonly

private, protected and readonly draw the fence

private members are reachable only inside the class body, protected also inside subclasses, and readonly ones can be assigned only where they are declared or in the constructor.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A balance nobody outside can set directly is a balance that cannot go negative behind the class's back. The fence is enforced at compile time, before the code ever runs.

How to think about it

Default to private for state, expose it through methods, and open it to protected only when a subclass needs it. Mark identifiers and configuration readonly so a later assignment is refused.

Worked example

class Account {
  private balance: number;
Only the class body may touch it.
  readonly id: number;
Set once, in the constructor.
  constructor(id: number, balance: number) { this.id = id; this.balance = balance; }
  deposit(n: number): number { this.balance += n; return this.balance; }
The only door to balance.
}
const a = new Account(7, 100);
console.log(a.deposit(50), a.id);
150 7

Your turn

Keep the balance reachable only through methods.

class Wallet {
   coins: number = 0;
  add(n: number) { this.coins += n; }
}

The trap

Believing private hides the value at runtime. The emitted JavaScript still has the property; the fence exists only in the compiler. Use #private for a runtime guarantee.

Practise private, protected, readonly on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.