Encapsulation
easy 35 minPut the data and the methods that work on it into one unit, and let outside code reach the data only through those methods.
Watch lesson4:51
The unit of hiding
Object, class, package, module, service: where the wall stands, and which wall pays.
The point: encapsulation is not only about classes. Choose the smallest unit whose inside changes together, and put the wall around that.
Private to what?
| Unit | Example | Who is inside |
|---|---|---|
| Object | Smalltalk instance variables | only this one object |
| Class | Java and C++ private, JavaScript # | all objects of the class: equals may read the other one's fields |
| Package or crate | Java package access, Rust pub(crate) | neighbours in the same directory or build |
| Module | Kotlin internal, Go internal/ directories, Node exports | everything built or shipped together |
| Service | HTTP API, with its own database | one team |
class Money: def __init__(self, cents): self.__cents = cents # renamed to _Money__cents def same_as(self, other): return self.__cents == other.__cents # allowed: same classprint(Money(5).same_as(Money(5)))print([name for name in vars(Money(5))])Two classes, one secret
A LinkedList and its Node know each other's fields. Making Node private to the list is right: the pair is the unit. The same holds for an order and its lines, or a parser and its tokens. If you find getters that exist for one neighbour only, the wall stands too close.
One package, one door
1/3The door
One public class. Other packages see quote and the Quote value.
usesowns (dies together)
Choosing the wall
Where should the border go?
Trade-offs. A wider wall is easier to work inside and harder to keep clean. A narrower wall gives more walls, more accessors and more ceremony. A service wall is the strongest, because nothing but the API exists for others, and it costs a network call, versions and partial failure. Do not buy that wall for hiding alone.
- Shared database tables break a service wall the way public fields break a class.
- A public test helper in the main package is a hole in the wall.
- Reflection and friend declarations are doors with a written reason, or they should not exist.