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
Extract Class
Replace Data Value with Object
Encapsulate Composite with Builder
Introduce Parameter Object
Move Embellishment to Decorator
Replace Conditional Logic with Strategy
Replace Implicit Tree with Composite
Replace Type Code with Class
Replace Type Code with State/Strategy
Replace Type Code with Subclasses
Replace Array With Object
Reference
Last updated