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.name is clearer than row[0].
  • Type Safety: Arrays are usually loose with types.

Mechanics (Steps)

  1. Create a class to represent the data.
  2. Add a field for each array index.
  3. 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
  • Documented fields
  • More code initially
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After