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
The type does not correspond to a variable's value (i.e., phone number as a string).
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"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
- ORIGIN1999 · ISBN 978-0201485677