Primitive Obsession Smell
What You'll Learn
You'll learn to recognize when overusing primitive types (strings, integers, floats) instead of creating small, meaningful objects leads to code that's harder to understand and maintain.
The Core Problem
Primitive Obsession occurs when you use basic data types like int, string, or float to represent domain concepts that deserve their own small classes or types. Instead of creating objects to model things like money, phone numbers, or date ranges, developers "obsess" over primitives and use them everywhere.
Think of it like using a screwdriver for everything when you need specialized tools. Sure, a screwdriver can pry open a can or hammer a nail, but it's not designed for those tasks.
Why It's Problematic
When you represent a phone number as a string or a price as a float, you lose:
- Type safety: Nothing prevents you from passing an email where a phone number belongs
- Validation: Primitive types don't enforce business rules (negative prices, invalid area codes)
- Behavior: Related operations scatter across the codebase instead of living with the data
- Clarity:
calculateDiscount(100.50, "USD")is less clear thancalculateDiscount(Money(100.50, Currency.USD))
Example Indicators
You're dealing with Primitive Obsession when you see:
- Multiple primitive parameters always passed together (
amountandcurrency) - Validation logic repeated everywhere (
if phoneNumber.length == 10) - Type-based branching (
if unit == "celsius"vsif unit == "fahrenheit") - Primitives with special formatting requirements
The Solution
Replace primitives with small value objects that encapsulate data and behavior. A Temperature class, PhoneNumber class, or Money class makes intent explicit and centralizes logic.
Key Takeaway: When primitives represent domain concepts, wrap them in small objects to add meaning, validation, and type safety—making your code more expressive and less error-prone.