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
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
One lever, one chute: the pan is mine.
A medicine capsule: a smooth shell outside, the powder inside. A piggy bank: coins go in by the slot, and nobody reaches in. A popcorn cart: a lever, a chute, a gauge, and an engine that can be replaced.
Cheat sheet
- Two halves
- bundle, hide
- Default
- private, open on demand
- Java
- private < package < protected < public
- UML
- - ~ # +
- Change
- actions with names, check first
- Read
- answers before raw values
- Set once
- `private final`, no setter
- Secret
- compare, never reveal
- Proof
- swap the inside, same tests
- Not for
- plain values without rules
Spot it when you see
- A value with limits
- Two fields that must agree
- A rule written in several callers
- “We may store this differently later”
Tricks that stick
- **CAPSULE:** Control access. Abstract the details. Protect fields with private. Setters check. Use getters to read. Limit visibility. Ensure integrity.
- Ask of each public member: who calls this, and what do they really want to know?
- Say the rule as a sentence first. Then find the class that has the data.
Do not forget
- A getter and setter for every field
- Protected fields as a habit
- The rule in the service, the data in the class
- Calling private a security feature
- Wrapping plain values