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 = 1for “O” blood.
Motivation
- Typos:
type = 99is valid for int but invalid for class. - Location for logic: Ensure behaviors related to the type are in the type class.
Mechanics (Steps)
- Create a class for the type code.
- 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 |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After