Encapsulate Collection
Encapsulate access to a collection field to prevent direct modification.
“A method returns a collection. Make it return a read-only view and provide add/remove methods.”
Protect your lists.
graph LR
A[Public List] -->|Refactoring| B[Private List + Add/Remove Methods]
When to apply (Smells)
- Leaking internal state: Clients modify the collection directly without the owner knowing.
Motivation
- Control: The owning class should control membership of the collection.
Mechanics (Steps)
- Add
add()andremove()methods. - Return a Read-Only copy (or iterator) in the getter.
Explanation
Problem
A class returns a reference to a collection field. getSkills().
The client then adds to it. person.getSkills().add('Java').
Solution
Return an unmodifiable list. person.getSkills() (read-only).
Provide person.addSkill('Java').
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After