Skip to content

Primitive Obsession: when strings and numbers fake domain concepts

Primitive Obsession is when raw strings, integers and floats stand in for money, ids, emails and date ranges, scattering validation and rules across your code.

6 min readCode smellBloat

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 amountCents and currency, or startDate and endDate.
  • 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()}`;
}

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 string or int gets 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.

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.

Next guide5 of 5 · Smells: bloatData ClumpsRead the next one