Ensuring proper encapsulation
medium 40 minPrivate fields are the start, not the end.
Video lesson · Chapter 1 of 6
Make a prediction
Ensuring proper encapsulation
1:01Reel
Theory
Read or listen first. About 2 min.
What it is
Encapsulation keeps data together with the methods that use it, and hides the data. This page is about doing it properly: can code outside the class still break the object, although every field is private?
Very often it can. A getter hands out the real list. A constructor keeps the caller's list. A setter accepts anything. Two threads call two correct methods between each other. Each of these is a door, and a sealed class has checked every door.
The test is one sentence: no sequence of calls from outside can make the rules of this object false. The rules are called invariants. A balance is never below the limit. A meeting starts before it ends. The total equals the sum of the lines.
Why it exists
If a rule can be broken from anywhere, then every line of the program is a suspect. If the rule can only be broken inside one class, the search is one file long. That is the practical value: bugs have an address.
It also buys freedom. When nobody outside touches the list, it may become a set, a database query or a cache next year, and no caller changes.
The price is real too: copies cost time and memory, and checks cost lines. So we also need to know when a copy is not needed. The best answer is usually not a copy but a value that cannot change, see Immutability.
A short history
1972
David Parnas publishes On the Criteria To Be Used in Decomposing Systems into Modules. It argues that each module should hide a design decision from the others. The idea is named information hiding.
2014
Java 8 ships
java.time. Its dates, such asLocalDate, cannot be changed. Most copies of the old changeableDatebecome unnecessary in new code.2021
Java 17 strongly encapsulates nearly all JDK internals (JEP 403). Even reflection is refused by default.
2022
ECMAScript 2022 includes private elements written with
#. The engine itself enforces them.
Words to know
- Invariant
- A statement about an object that is true between any two public calls. Example:
start < end. - Information hiding
- Callers do not know a decision, so the decision can change.
- Alias
- A second reference to the same object. Whoever holds it can change what you see.
- Defensive copy
- Your own copy of something changeable, made when it comes in or goes out.
- Shallow copy
- A new container with the same elements inside. Deep copy: the elements are copied too.
- View
- A read only window on a live collection. The holder cannot write, but sees later changes.
- Snapshot
- A copy that shows one moment and never changes.
- Representation exposure
- The inside of an object can be reached from outside, usually through a leaked reference.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Write the rules. What must always be true?
Understand it
One hatch, and it checks
Max and Asha keep ants. Follow what comes in, what goes out, and where somebody finds another way.
Glass alone is not the point. The point is that every way in and out is known.
A bank vault is the same idea with people: you do not walk in, a teller checks who you are, writes the visit into a ledger and gives you a receipt. The receipt is a copy. The ledger stays.
Private, and still broken
Every field below is private by convention, and there are only methods. The class can be broken in four ways. Run it.
class Team: def __init__(self, members): self._members = members # keeps the caller's list self._limit = 3 def members(self): return self._members # hands out the real list def set_limit(self, n): self._limit = n # accepts anything def add(self, name): if len(self._members) >= self._limit: raise ValueError("team is full") self._members.append(name)mine = ["asha"]team = Team(mine)mine.extend(["lee", "max", "noor"]) # 1. through the list we keptprint(len(team.members()), "members, limit 3")team.members().append("sam") # 2. through the list we gotprint(len(team.members()), "members")team.set_limit(-5) # 3. a limit that makes no senseteam._members = None # 4. Python lets you, the underscore asks you not toprint(team._members)Is sealed
- Private fields, and only the reads that callers need
- Returns values, snapshots or views
- Copies what it stores if it can change
- Checks in the class, once, for all callers
- Method names are actions:
deposit,give_raise,move_to
Looks sealed
- Private fields with a getter and a setter for each
- Returns the real list, map or date
- Stores the list it was given
- Checks in the user interface, not in the class
- Method names repeat the fields: the inside is visible in the names
The bad shape and the good shape
Everybody writes the balance
1/2A record with two public fields
Nothing protects the number. account.balance = -1000 is legal.
depends on
One class owns the rule
1/3State goes private
Balance and entries sit behind a minus sign. Nobody else can name them.
usesowns (dies together)
Four golden rules, with their reasons
Make fields private
If nobody can name a field, nobody can depend on it. Hide by default, open on demand. It is easy to open later and hard to close.
Check what enters
In the constructor and in every method that changes state. Refuse loudly. A silent ignore hides the bug of the caller.
Guard what leaves
Immutable value: return it. Changeable part: return a snapshot or a read only view. Better: answer the question they had.
Copy what stays
A list, map, array or date from outside is a string in the caller's hand. Copy it, and check the copy.
Who may see a member
| Language | Only the class | Near the class | Everyone | Enforced by |
|---|---|---|---|---|
| Java | private | no keyword: same package. protected: same package and subclasses | public | Compiler and JVM. Reflection can open it unless a module forbids it |
| C++ | private | protected: subclasses. friend: named others | public | Compiler only |
| TypeScript | private | protected: subclasses | public (default) | Type checker only. It disappears at run time |
| JavaScript | #field | none | default | The engine, at run time |
| Python | _field: please do not | __field: renamed to _Class__field, avoids name clashes in subclasses | default | Convention. Name mangling is not a lock |
protected also opens the member to the whole package. Many people forget this.Why a private list leaks
Variables hold references. Passing a list passes the reference, so after the call two parties hold the same list. The word private protects the variable, not the thing it points to.
The same date, two owners
The same calls with copies
What to do with each kind of value
Copy or not?
Tools per language
| Need | Java | Python | TypeScript | C++ |
|---|---|---|---|---|
| Snapshot of a list | List.copyOf(xs) | tuple(xs) | [...xs] as readonly T[] | return by value |
| Snapshot of a set | Set.copyOf(s) | frozenset(s) | new Set(s) | return by value |
| Live read only view | Collections.unmodifiableList(xs) | MappingProxyType(d) for dicts | readonly T[] (types only) | const std::vector<T>&, std::span<const T> |
| Frozen object | record with copies in its constructor | @dataclass(frozen=True) | Object.freeze(o) | const members or value type |
| Deep copy | copy constructor | copy.deepcopy | structuredClone(o) | copy constructor |
record, frozen=True and Object.freeze are shallow: a list inside is still changeable.Do we need a setter at all?
A setter with a check is better than a public field. An action is better than a setter, because it says what happened. set_salary(82500) cannot know whether this is a raise, a correction or a mistake. give_raise(10) can check the limit and write the history. The general rule is Tell, don't ask.
A Cart must let the page show its items and change quantities. What do you expose?
BreaksgetItems() returns the list
- How
- The page reads and edits the list. Short to write.
- Limit
- Quantities of -3, a total that does not match, no event when something changes.
- Choose when
- Never for state with rules.
WorksA copy out, a setter in
- How
items()returns a snapshot,setItems(list)checks and replaces all.- Limit
- Two tabs: the second replaces the first one's change. The check runs over everything.
- Choose when
- Small forms that are saved as a whole.
StrongSnapshot out, actions in
- How
items()gives values,change_quantity(sku, n)checks one thing and updates the total.- Limit
- More methods. Each is a decision about what callers may do.
- Choose when
- State with rules. This is the normal case in an interview.
A life with only valid states
Nothing invalid is ever visible
The last arrow is the one people forget. Do all checks and all work that can fail before the first write. Then an error leaves the object as it was.
When a sealed class is too much
A bundle of values that may vary independently has no invariant to protect. The C++ Core Guidelines say it in rule C.2: use a class if there is an invariant, use a struct if the members can vary independently. A request body, a row for a report, a config record: make it an immutable value and stop.
| Thing | Rule inside? | Good form |
|---|---|---|
| Point, colour, request body | no | frozen dataclass, record, readonly type |
| Email, Money, DateRange | yes, on creation only | immutable value with a checking constructor |
| BankAccount, Meeting, Cart | yes, over time | class with private state and actions |
| Hot loop over a million numbers | internal to one module | plain array, kept private in the module |
Neighbours of this idea
Encapsulation is the basic concept. Law of Demeter is about reaching through an object. Immutability removes most copies. Achieving modularity does the same sealing one size larger, for whole modules.
Summary
The whole topic in one minute.
An object is properly encapsulated when no call from outside can make its rules false. Private fields are needed, but references leak through constructors, getters, callbacks and subclasses. Every one of these is a door to check.
Copy changeable input before checking it, return values or snapshots, and offer actions instead of setters. Use immutable values wherever you can: they need no copies. And do not seal what has no rule.
- Write the invariants down. They decide what to protect.
- Private hides a name. Leaks happen through references.
- Copy changeable input first, then check the copy.
- Return values, snapshots or views. Best: answer the question.
- Offer actions, not setters. Fail before the first write.
- Immutable values need no copies. Values without rules need no class.