Replace Data Value with Object

Turn a dumb data item into a smart object.

“Code has a data item that needs additional data or behavior.”

Primitive Obsession cure.

graph LR
    A[String 'Customer'] -->|Refactoring| B[Customer Object]

When to apply (Smells)

  • Primitive Obsession: Using strings or numbers for complex concepts (like Phone Number, Money).

Motivation

  • Encapsulate logic: Move behavior related to the data into the new class.

Mechanics (Steps)

  1. Create a class for the data.
  2. Provide a constructor.
  3. Change the type in the main class to the new class.

Explanation

Problem

You have a data field (like a string for “Customer Name”) that starts needing more logic (parsing, formatting).

Solution

Turn the data field into an object (“Customer”) that holds the data and behavior.

Real world analogy

Instead of writing “John Doe” on a sticky note, you create a “Person/Employee Record” that has name, ID, and phone number slots.

Pros and Cons

Pros Cons
  • Encapsulates behavior
  • More classes
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After