Primitive Obsession is when a domain concept with its own rules is passed around as a bare string, number or int. A price becomes an integer of cents next to a separate currency string. A member id becomes any string. A booking period becomes two loose date strings that nobody checks are in order.
The primitives themselves are fine. The trouble is that the rules belonging to the concept have nowhere to live, so they get copied into every function that touches the value: the regex for ids, the @ check for emails, the cents-to-decimal formatting, the start-before-end check. Each copy drifts a little, and the type system can't stop you passing a desk id where a member id was expected.
In interviews this smell comes up in design and code review questions. Spotting it, and knowing when a small value object is worth adding, shows you think about invariants, not just syntax.
Signs
How to spot it in a review.
- The same regex, range check or format conversion appears in several functions for one kind of value.
- Pairs of fields always travel together, such as
amountCentsandcurrency, orstartDateandendDate. - Several parameters share a type like
string, so swapping two arguments still compiles. - Names carry the meaning the type should:
priceCents,emailStr,isoDate,userIdString. - Arithmetic on a value is done by hand at call sites, like dividing by 100 and padding to two decimals.
- Constants or string codes stand in for a small set of allowed values, like
"EUR"checked with===everywhere.
What it looks like
A typical case, in three languages.
interface Booking {
memberId: string;
billingEmail: string;
deskId: string;
startDate: string; // "2024-05-01"
endDate: string;
dailyRateCents: number;
currency: string;
}
const MS_PER_DAY = 24 * 60 * 60 * 1000;
export function quoteBooking(booking: Booking, discountPercent: number): string {
if (!/^mem_[a-z0-9]{8}$/.test(booking.memberId)) {
throw new Error(`Invalid member id: ${booking.memberId}`);
}
if (!booking.billingEmail.includes("@")) {
throw new Error(`Invalid email: ${booking.billingEmail}`);
}
if (booking.endDate < booking.startDate) {
throw new Error("End date is before start date");
}
const days =
Math.round((Date.parse(booking.endDate) - Date.parse(booking.startDate)) / MS_PER_DAY) + 1;
const gross = booking.dailyRateCents * days;
const net = Math.floor((gross * (100 - discountPercent)) / 100);
const amount = `${Math.floor(net / 100)}.${String(net % 100).padStart(2, "0")}`;
return `${amount} ${booking.currency} for ${days} days, invoice to ${booking.billingEmail.toLowerCase()}`;
}import re
from dataclasses import dataclass
from datetime import date
@dataclass
class Booking:
member_id: str
billing_email: str
desk_id: str
start_date: str # "2024-05-01"
end_date: str
daily_rate_cents: int
currency: str
def quote_booking(booking: Booking, discount_percent: int) -> str:
if not re.fullmatch(r"mem_[a-z0-9]{8}", booking.member_id):
raise ValueError(f"Invalid member id: {booking.member_id}")
if "@" not in booking.billing_email:
raise ValueError(f"Invalid email: {booking.billing_email}")
if booking.end_date < booking.start_date:
raise ValueError("End date is before start date")
days = (date.fromisoformat(booking.end_date) - date.fromisoformat(booking.start_date)).days + 1
gross = booking.daily_rate_cents * days
net = gross * (100 - discount_percent) // 100
amount = f"{net // 100}.{net % 100:02d}"
return f"{amount} {booking.currency} for {days} days, invoice to {booking.billing_email.lower()}"<?php
final class Booking
{
public function __construct(
public string $memberId,
public string $billingEmail,
public string $deskId,
public string $startDate, // "2024-05-01"
public string $endDate,
public int $dailyRateCents,
public string $currency,
) {}
}
function quoteBooking(Booking $booking, int $discountPercent): string
{
if (!preg_match('/^mem_[a-z0-9]{8}\z/', $booking->memberId)) {
throw new InvalidArgumentException("Invalid member id: {$booking->memberId}");
}
if (!str_contains($booking->billingEmail, '@')) {
throw new InvalidArgumentException("Invalid email: {$booking->billingEmail}");
}
if ($booking->endDate < $booking->startDate) {
throw new InvalidArgumentException('End date is before start date');
}
$start = new DateTimeImmutable($booking->startDate);
$end = new DateTimeImmutable($booking->endDate);
$days = $start->diff($end)->days + 1;
$gross = $booking->dailyRateCents * $days;
$net = intdiv($gross * (100 - $discountPercent), 100);
$amount = sprintf('%d.%02d', intdiv($net, 100), $net % 100);
$email = strtolower($booking->billingEmail);
return "{$amount} {$booking->currency} for {$days} days, invoice to {$email}";
}This quote function for a coworking desk-booking service validates a member id, an email and a date range, then does money maths and formatting by hand. Every other function that touches bookings, such as invoicing or refunds, needs the same checks and will copy them. Nothing stops a caller swapping memberId and deskId, or adding EUR cents to GBP cents. Pulling out MemberId, EmailAddress, DateRange and Money lets each concept validate itself once in its constructor, and shrinks this function to the pricing rule it actually owns.
Why it happens
How code ends up like this.
- Adding a class for a single value feels heavyweight at first, so a
stringorintgets used as a placeholder and never replaced. - Values arrive as primitives from JSON, forms and database rows, and it is easiest to keep them that way all the way down.
- Rules are added one at a time: first a format check, later a normalisation step, then a currency, each patched in at the call site that needed it.
- Some languages make small types awkward, so teams avoid them even when the domain clearly has them.
Treatment
The refactorings that cure it, and when to choose each.
- Replace Primitive with Object: Give Rule-Bearing Values a Type
A single value like a member id, email or amount has its own validation or behaviour. Wrap it in a small immutable type that rejects bad input in its constructor.
- Introduce Parameter Object: Bundle Parameters That Travel Together
Two or more primitives always travel together, such as start and end dates or cents and currency. Group them into one object like
DateRangeorMoney. - Move Function: Put Behaviour Next to the Data It Uses
Logic that operates on the value, like counting days in a range or formatting an amount, sits in callers. Move it onto the new type so it exists in one place.
- Extract Class: Split a Class That Does Two Jobs
A larger class holds a cluster of related primitive fields plus the methods that manage them. Pull that cluster out into its own class.
- Replace Conditional with Polymorphism: One Class per Case
A string or integer type code drives
iforswitchchains across the codebase, and each code needs different behaviour, not just a different label. - Change Function Declaration: Fix a Signature Without Breaking Callers
Once the value objects exist, update signatures to accept them instead of raw primitives, so the compiler or type checker catches swapped arguments.
Payoff
What you get once it's gone.
- Validation runs once, at construction, so invalid ids, emails and ranges cannot reach business logic.
- Function signatures document themselves and argument mix-ups become type errors.
- Money and range arithmetic lives in one tested place instead of being redone by hand at each call site.
- Business functions get shorter and read as the domain rule they implement.
When to leave it
Sometimes it's not worth fixing.
- At system boundaries, such as parsing a request body or writing a database row, primitives are the natural format. Convert to value objects right after parsing and back right before writing.
- A value with no rules of its own, like a free-text note or a display label, gains little from being wrapped.
- In a throwaway script or a one-off migration, the cost of new types may outweigh the benefit.
Common questions
Short answers to the usual doubts.
Isn't wrapping a string in a class just extra boilerplate?
It is a few lines, and it pays off once the value has a rule. Without the type, that rule is copied into every function that handles the value, and the copies drift. With it, the rule lives in one constructor. In TypeScript a branded type or a small class works; in Python a frozen dataclass; in PHP a final readonly class.
Why not store money as a float?
Binary floating point cannot represent most decimal fractions exactly, so sums and discounts pick up rounding errors. Use integer minor units or a decimal type, and keep the currency with the amount in a Money object so you cannot add two different currencies by accident.
How do value objects interact with ORMs and JSON serialisation?
Most ORMs support embedded or custom-mapped types, and most serialisers let you register a converter. Where that is awkward, map at the repository or controller layer: read primitives, build value objects, and convert back on the way out. The domain code in the middle only sees the rich types.
How should I bring this up in a code review interview?
Point to a concrete symptom, such as the same email check in three places or two adjacent string parameters that can be swapped. Propose one value object for the concept with the most rules, show its constructor validating input, and explain that you would migrate call sites gradually rather than rewriting everything at once.
Should every id in the system get its own type?
Not necessarily. Distinct id types are most valuable where different kinds of ids are passed side by side and easy to confuse, like member and desk ids in the same function. For an id used in only one module with no format rules, a plain string is usually fine.