Ensuring proper encapsulation
medium 40 minPrivate 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 write | Say |
|---|---|
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
Interviewer
Your parking lot returns its list of spots. Fine?
You
No. A caller could clear it, and tickets would point to spots that the lot no longer knows. What does the caller need?
Interviewer
How many are free, per type.
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.Interviewer
And if copying is slow?
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.