Home Knowledge Base Primitive Obsession

Primitive Obsession is a code smell where domain concepts with semantic meaning, validation requirements, and associated behavior are represented using primitive typesString, int, float, boolean, or simple arrays — instead of small, focused domain objects — creating code where "a phone number" is just any string, "a price" is just any floating-point number, and "a user ID" is interchangeable with "a product ID" at the type level, eliminating the compile-time safety, centralized validation, and encapsulated behavior that dedicated domain types provide.

What Is Primitive Obsession?

Primitive Obsession manifests in identifiable patterns:

Why Primitive Obsession Matters

The Strangler Pattern for Primitive Obsession

Martin Fowler's Tiny Types approach: create minimal wrapper classes for each semantic concept, initially just wrapping the primitive with validation:

# Before: Primitive Obsession
def create_user(email: str, age: int, phone: str) -> int:
    if "@" not in email: raise ValueError("Invalid email")
    if age < 0 or age > 150: raise ValueError("Invalid age")
    ...

# After: Domain Types
@dataclass(frozen=True)
class Email:
    value: str
    def __post_init__(self):
        if "@" not in self.value:
            raise ValueError(f"Invalid email: {self.value}")

@dataclass(frozen=True)
class Age:
    value: int
    def __post_init__(self):
        if not (0 <= self.value <= 150):
            raise ValueError(f"Invalid age: {self.value}")

@dataclass(frozen=True)
class UserId:
    value: int

def create_user(email: Email, age: Age, phone: PhoneNumber) -> UserId:
    ...  # Validation has already happened in the domain type constructors

Common Primitive Obsessions and Their Replacements

PrimitiveReplacementBenefits
float for moneyMoney(amount, currency)Exact decimal arithmetic, currency safety
str for emailEmail(address)Validated format, normalization
int for user IDUserId(int)Type safety, prevents ID confusion
str for statusOrderStatus enumExhaustive pattern matching, autocomplete
str for URLURL(str)Validated format, path extraction
str for phonePhoneNumber(str)E.164 normalization, formatting

Tools

Primitive Obsession is fear of small objects — the reluctance to create dedicated types for domain concepts that results in a flat, semantically undifferentiated model where every concept is "just a string" or "just an integer," trading type safety, centralized validation, and encapsulated behavior for the illusion of simplicity that ultimately costs far more in scattered validation, silent type errors, and missed business logic concentration opportunities.

primitive obsessioncode ai

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.