Primitive Obsession

The excessive use of basic data types to represent concepts or entities in code.

Sign of Smell

Primitive Obsession refers to the overuse or excessive reliance on primitive data types (e.g., integers, strings, booleans) to represent certain concepts or entities in the code.

People who are new to object-oriented programming often hesitate to use small objects for simple tasks. For example, they may not consider creating a money class that combines numbers and currency, a range class with an upper and lower bound, or special string classes for telephone numbers and ZIP codes.

Reason of Smell

  • Lack of Reusability: When developers rely on primitive data types instead of creating custom classes or objects, it limits the reusability of code. Custom type classes can encapsulate behavior and data, making it easier to reuse them in different parts of the codebase. Primitives, on the other hand, lack this encapsulation, making it harder to reuse them effectively.

  • Lack of Abstraction: Primitive Obsession often leads to a lack of abstraction in the code. When the codebase is littered with primitives, it becomes challenging to understand the higher-level concepts and business logic. This can make the code harder to maintain, extend, and reason about.

  • Code Duplication: When similar functionality or behavior needs to be implemented for multiple instances of the same primitive, developers may end up duplicating code. This duplication can lead to inconsistencies and maintenance headaches. For example, all user-like classes should share the same validation logic for valid telephone number fields, rather than duplicating it in multiple places.

  • Limited Behavior: Primitives have limited behavior and capabilities compared to custom classes or objects. By using primitives, developers may miss out on the benefits of encapsulation, data validation, and behavior associated with a custom class.

  • Increased Complexity: As the codebase grows, the reliance on primitives can increase the overall complexity of the code. This makes the code harder to understand and modify.

Refactoring Recipe

  1. Extract Class

  2. Replace Data Value with Object

  3. Encapsulate Composite with Builder

  4. Introduce Parameter Object

  5. Move Embellishment to Decorator

  6. Replace Conditional Logic with Strategy

  7. Replace Implicit Tree with Composite

  8. Replace Type Code with Class

  9. Replace Type Code with State/Strategy

  10. Replace Type Code with Subclasses

  11. Replace Array With Object

Reference

https://refactoring.guru/smells/primitive-obsession

Last updated