Replace Array with Object
Replace an array that holds different types of data with an object.
“You have an array in which certain elements mean different things.”
Structs over Arrays.
graph LR
A[Array ['John', '123']] -->|Refactoring| B[Object {name, id}]
When to apply (Smells)
- Mysterious array usage:
data[0]is name,data[1]is age.
Motivation
- Readability:
person.nameis clearer thanrow[0]. - Type Safety: Arrays are usually loose with types.
Mechanics (Steps)
- Create a class to represent the data.
- Add a field for each array index.
- Replace array usage with the object.
Explanation
Problem
You use an array to store data about an item. ['Liverpool', '15'].
Solution
Replace it with an object. new Team('Liverpool', 15).
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After