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

When it comes up

The moments this idea belongs in a design interview, and the moments it does not.

When to bring it up

You see or hearSay
A class with data and a service with all its rules“I move the rule to the data, then the field can be private.”
“Add a setter for that”“Which event changes it? I would name the method after the event.”
A balance, a stock count, a seat state“This has limits, so it changes only through checked actions.”
A request or response class“No rules inside. A plain record.”
“What if the storage changes?”“Callers see two methods. I can replace the number by a ledger.”

In the room

  1. Interviewer

    Your ParkingSpot has a public boolean free. Is that a problem?

  2. You

    Yes. Two parts of the code could both set it to false for two cars. I would make it private and offer try_park(vehicle), which checks and sets in one step and returns whether it worked.

  3. Interviewer

    The display needs to know which spots are free.

  4. You

    Then a question, is_free(), without a setter. Or better, the lot answers free_count(type), because that is what the display shows.

  5. Interviewer

    Should everything be private?

  6. You

    State with rules, yes. The Ticket I return is a plain value with number, spot and time. It has no rule to protect.

How do you define encapsulation in one minute?

Breaks“Private fields with getters and setters”
How
The textbook reflex.
Limit
The next question is: what does that protect? Often nothing.
Choose when
Avoid it.
Works“Bundle data with methods and restrict access”
How
Correct definition.
Limit
Says nothing about why.
Choose when
As the first sentence.
StrongDefinition, rule, freedom
How
“Data with its methods, access restricted. So the rules hold in one place, and I can swap the inside. For example the balance could become a ledger.”
Limit
Keep it under a minute.
Choose when
The default.