Primitive Obsession — Code Smells Catalog Skip to content

Primitive Obsession

Bloaters Data Code Smell Between Class

A phone number stored as a string. A price stored as a float. Concepts that deserve their own types get crammed into primitives, losing validation, scattering logic, and pretending a bare string...

2 min read 1 source

Overview

Whenever a variable that is just a simple string, or an int simulates being a more abstract concept, which could be an object, we encounter a Primitive Obsession code smell. This lack of abstraction quickly becomes a problem whenever there is the need for any additional logic, and also because these variables easily spread wide and far in the codebase. This alleged verbal abstraction is just a “supposed” object, but it should have a real object instead.

Causation

Possibly a missing class to represent the concept in the first place. Mäntylä gives an example of representing money as primitive rather than creating a separate class [1], and so does Fowler, who states that many programmers are reluctant to create their own fundamental types. [2]. Higher-level abstraction knowledge is needed to clarify or simplify the code. 3

Problems

🔍
Hidden Intention

The type does not correspond to a variable's value (i.e., phone number as a string).

📦
Lack of Encapsulation

These primitives often go in groups, and there’s a lack of written relations between them, and nothing protects them from external manipulation.

Example

1birthday_date: str = "1998-03-04"
2name_day_date: str = "2021-03-20"
PYTHON

Refactoring

  • Replace Data Value with Object
  • Extract Class
  • Introduce Parameter Object
  • Replace Array with Object
  • Replace Type Code with Class
  • Replace Type Code/Conditional Logic with State/Strategy
  • Move Embellishment to Decorator

Sources

Browse All 56 Smells