Change Value to Reference
Turn a value object into a reference object.
“You have a class with many equal instances that you want to replace with a single object.”
Singleton-ish behavior for entities.
graph LR
A[Many 'Customer' Copies] -->|Refactoring| B[Shared 'Customer']
When to apply (Smells)
- Data inconsistency: Updating one copy doesn’t update others.
Motivation
- Ensure that changes to one conceptual object (like a Customer) are reflected everywhere.
Mechanics (Steps)
- Replace the constructor with a Factory Method.
- Make the factory method return existing instances if available (Repository pattern).
Explanation
Problem
You create a new object for the same entity every time (e.g., new Customer(“John”)). If you change John’s address in one order, it doesn’t update in another order.
Solution
Convert the object to a reference object so all orders point to the same Customer instance.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Inverse Refactoring: Change Reference to Value.
Code example
Typescript
Before
After
PHP
Before
After