Hide state behind methods
Protect an object's rules by keeping its data private.
Public fields break rules
If a wallet's balance is a public field, any code can set it to minus a million. The rule "you cannot overdraw" now depends on every caller remembering it.
Make the field private and expose methods that enforce the rule. The object guards itself.
class Account {
private balance = 0;
withdraw(amount: number) {
if (amount > this.balance) throw new Error("Not enough money");
this.balance -= amount;
}
get current() { return this.balance; }
}
Return copies, not internals
Returning your internal array lets callers change it. Return a copy or a read-only view so history cannot be edited from outside.
Key takeaways
- Private state, public behaviour.
- Validate inside the method that changes state.
- Return copies of internal lists.
Hands-on coding exercise
A bank account whose balance can only change through deposit and withdraw. Both reject amounts of 0 or less, and withdraw refuses to go below zero.
Keep the balance private and expose it read-only, so no code outside can set it.
class Account {
get balance(): number {
throw new Error("Not implemented");
}
deposit(amount: number): void {
throw new Error("Not implemented");
}
withdraw(amount: number): void {
throw new Error("Not implemented");
}
}
Run your solution against 5 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- Why make a balance field private?
- history() returns this.entries directly. What can go wrong?