AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

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 hear or writeSay
getItems() in your own code“This leaks the list. I return a snapshot.”
A constructor that takes a list“I copy it, the caller may keep theirs.”
Two linked fields“One method changes both.”
if (x.get...) x.set... in a caller“That check belongs inside.”
Threads“Check and act are one method under a private lock.”

In the room

  1. Interviewer

    Your parking lot returns its list of spots. Fine?

  2. You

    No. A caller could clear it, and tickets would point to spots that the lot no longer knows. What does the caller need?

  3. Interviewer

    How many are free, per type.

  4. You

    Then I offer free_count(type) and drop the list. If the sign needs all spots, I return a tuple of small immutable summaries.

  5. Interviewer

    And if copying is slow?

  6. You

    I keep counters up to date on each park and leave, so the sign reads two integers.

How do you protect List<Item> items in an interview class?

Breaksprivate and a getter
How
The usual generated code.
Limit
Anyone can clear the list.
Choose when
Never for state with rules.
WorksSnapshot getter
How
List.copyOf(items).
Limit
Elements may still be changeable, and callers see the structure.
Choose when
Elements are immutable.
StrongActions and questions
How
add(item), total(), contains(sku), snapshot only for display.
Limit
More methods to design.
Choose when
The default for entities.