Self Encapsulate Field
Access a field through getters and setters even inside the class.
“You are accessing a field directly, but the coupling to the field is becoming awkward.”
Indirect access to internal data.
graph LR
A[Direct Access] -->|Refactoring| B[Getter/Setter]
When to apply (Smells)
- Low flexibility: You want to override the field access in a subclass.
- Lazy Loading: You need to calculate the value on the fly.
Motivation
- De-coupling: Subclasses can override how data is retrieved.
Mechanics (Steps)
- Create a getter (and setter) for the field.
- Find all direct accesses to the field.
- Replace them with the getter/setter.
Explanation
Problem
You access a field directly, but you need to add logic (like validation or lazy loading) to that access.
Solution
Wrap the field in a getter and setter and use them everywhere.
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After