AlgoViz

Encapsulation

easy 35 min

Put 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?

UnitExampleWho is inside
ObjectSmalltalk instance variablesonly this one object
ClassJava and C++ private, JavaScript #all objects of the class: equals may read the other one's fields
Package or crateJava package access, Rust pub(crate)neighbours in the same directory or build
ModuleKotlin internal, Go internal/ directories, Node exportseverything built or shipped together
ServiceHTTP API, with its own databaseone team
Python
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))])
Class level privacy. Two objects of one class are friends. The double underscore is a rename, meant against clashes in subclasses, and it is not a lock.
Edit and run it in your browser

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

Pricing+ quote(cart): Quote

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.