Replace Type Code with Class

Replace a primitive type code with a class.

“A class has a numeric type code that doesn’t affect its behavior.”

Enums on steroids.

graph LR
    A[Type = 1] -->|Refactoring| B[Type = BloodGroup.O]

When to apply (Smells)

  • Primitive Obsession: Using int type = 1 for “O” blood.

Motivation

  • Typos: type = 99 is valid for int but invalid for class.
  • Location for logic: Ensure behaviors related to the type are in the type class.

Mechanics (Steps)

  1. Create a class for the type code.
  2. Replace the field with the new class.

Explanation

Problem

Class has a field type which is an int/string constants.

Solution

Create a new class BloodGroup and use instances of it.

Pros and Cons

Pros Cons
  • Type safety
  • More boilerplate
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After