Encapsulation: Private Data and Invariants
Protect an object's data with private fields and methods that enforce invariants, so no outside code can put the object into an invalid state.
Welcome back!
Step 1 of 14Learn
The $1 million bug that wasn't a hack
A small payments team once shipped a Wallet class with a public balance field. The withdraw() method checked for overdrafts properly. But six months later, a developer writing a refund feature needed to adjust a balance and simply wrote wallet.balance -= amount. No check, no log entry, no event. Over a weekend, a rounding bug in that one line produced negative balances in thousands of wallets.
The withdraw() method was correct. It just wasn't the only way in.
Encapsulation means an object keeps its data private and offers a small set of public methods as the only way to read or change it. The goal is to protect the object's invariants: the rules that must always be true for the object to make sense.
For a wallet, the invariants might be:
- the balance is never negative;
- every change to the balance creates a transaction record;
- the balance always equals the sum of the transaction records.
If outside code can write to balance directly, no amount of careful coding inside the class can guarantee these rules. If the only path is through methods, then checking the methods is enough to prove the rules hold everywhere. That's the real payoff: you can reason about one class instead of the whole codebase.
Step 2 of 14Practice · Select all that apply
Which of these are reasonable invariants for a Calendar event object? Select all that apply.
Select all that apply.
Step 3 of 14Learn
Private fields in practice
Modern JavaScript marks private fields with a # prefix. They can be used only inside the class body; any access from outside is a syntax error.
class Wallet {
#balance = 0;
#history = [];
deposit(amount) {
if (amount <= 0) throw new Error('Deposit must be positive');
this.#balance += amount;
this.#history.push({ type: 'deposit', amount });
}
withdraw(amount) {
if (amount <= 0) throw new Error('Withdrawal must be positive');
if (amount > this.#balance) throw new Error('Insufficient funds');
this.#balance -= amount;
this.#history.push({ type: 'withdraw', amount });
}
get balance() { return this.#balance; } // read-only from outside
}
const w = new Wallet();
w.deposit(50);
w.balance; // 50
w.balance = 1e6; // no setter: ignored (TypeError in strict mode)
// w.#balance // SyntaxError outside the classOther languages offer the same protection with keywords: Java, C# and C++ have private, protected and public. Python takes a softer approach: a leading underscore (self._balance) is a strong convention meaning "internal, don't touch", and a double underscore triggers name mangling, but nothing is truly locked. Python developers rely on the convention, and it works because teams respect it.
Notice the read-only getter. Outside code can see the balance but can only change it through deposit() and withdraw(), where the rules live.
Step 4 of 14Practice · Diagram
The Wallet's public surface
Which member can no code outside the class ever change directly?
Tap the shape that answers the question, then press Check.
- Wallet
- + deposit(amount)
Checks the amount, then records the change.
- + withdraw(amount)
Checks amount and funds before changing anything.
- + get balance
Read-only view of the private value.
- − #balance
Only code inside the class can read or write it.
- − #history
Every change is logged here, keeping the invariant.
Step 5 of 14Practice · Spot the mistake
This class is supposed to keep a Thermostat target between 10 and 30 degrees at all times. Click the lines that break encapsulation or the invariant.
Step 6 of 14Learn
Validate at the boundary, then trust inside
Where should the checks go? The rule of thumb is validate at the boundary: every public method and the constructor check their inputs, because that's where data from the outside world enters. Once data is inside and valid, private helper methods can trust it instead of re-checking at every step.
A good public method follows a simple shape:
- Check the arguments and the current state. Throw a clear error if something is wrong.
- Change the fields, keeping every invariant true.
- Report: return a result or record what happened.
Order matters. If withdraw() subtracted first and then discovered the amount was invalid, the object would be left half-changed. Check everything first, then change.
Another common leak is returning internal objects. If getHistory() returns this.#history itself, the caller receives a reference to the private array and can push() fake transactions into it. Encapsulation fails without any public field at all. Return a copy instead:
getHistory() { return [...this.#history]; } // a new array; the original stays privateThe same applies to incoming objects. If a constructor stores an array the caller passed in, the caller still holds a reference and can change it later. Copy on the way in, too, when the object must stay in control of its data.
Step 7 of 14Practice · Diagram
The shape of a safe public method
Which step must be completely finished before any field is touched?
Tap the shape that answers the question, then press Check.
- Check
Validate arguments and current state. Throw a clear error if anything is wrong.
- Change
Update fields, keeping every invariant true.
- Report
Return a result or record what happened. Hand out copies, not internal objects.
Step 8 of 14Practice · Choose one
A Team class keeps a private array of players and exposes getPlayers() { return this.#players; }. What problem does this create?
Step 9 of 14Practice · Code challenge
Write a class BankAccount with a private field #balance starting at 0. Add deposit(amount) and withdraw(amount) that each return true on success and false (changing nothing) when the request is invalid. Invalid means: amount is not greater than 0, or a withdrawal larger than the balance. Add a getter balance that returns the current balance.
(() => { const a = new BankAccount(); a.deposit(100); a.withdraw(30); return a.balance; })()(() => { const a = new BankAccount(); a.deposit(50); return a.withdraw(80); })()(() => { const a = new BankAccount(); a.deposit(50); a.withdraw(80); return a.balance; })()(() => { const a = new BankAccount(); return a.deposit(-5); })()(() => { const a = new BankAccount(); a.deposit(0); a.balance = 999; return a.balance; })()
Step 10 of 14Learn
Encapsulation at every scale
Encapsulation isn't only about the fields of a single class. The same idea, hide the details and expose a small, deliberate surface, appears at every level of software.
- Functions hide their local variables. Nothing outside a function can reach a variable declared inside it.
- Modules hide everything they don't
export. A JavaScript file that exports onlycreateInvoicecan change its internal helpers freely. - Services hide their databases behind an API. Other teams send requests to a payments service; they never write directly to its tables.
The payoff is the same at each scale: the hidden part can change without breaking anyone, because nobody depends on it. A team that keeps its fields private can switch a balance from a number to integer cents, or a list of items from an array to a Map, and no caller notices.
That's why encapsulation is worth the small extra effort of writing methods. A public field is a promise to every caller that the data will always be stored exactly that way. A method is a promise only about behavior, and behavior is much easier to keep stable than storage.
Step 11 of 14Diagram
Encapsulation at every scale
Tap a shape with to see more.
- Services
Hide their database behind an API.
- Modules
Hide everything they do not export.
- Classes
Hide private fields behind methods.
- Functions
Hide local variables.
Step 12 of 14Practice · True or false
If a class keeps its fields private, its developers can change how the data is stored internally without breaking code that uses the class, as long as the public methods behave the same.
Step 13 of 14Note
Step 14 of 14Practice · True or false
Encapsulation means a class should have no public methods at all, so that nothing outside can affect it.
Lesson complete!