Skip to content

Replace Primitive with Object: Give Rule-Bearing Values a Type

Learn how to turn a raw string or number that carries rules, such as an email address, into a small validated type that owns those rules.

7 min readRefactoring

Some values look like plain strings or numbers but come with rules. An email address must be trimmed, lowercased and checked before you trust it. A price needs a currency and must never be negative. When these values travel around your code as bare primitives, every function that touches them has to remember the rules again. Replace Primitive with Object wraps such a value in a small class that checks its rules once, at creation, and exposes the operations that make sense for it. In this guide you will refactor the invite flow of Tallyboard, an invented team-planning tool, where email addresses are passed around as raw strings.

The problem

A situation where the obvious design starts to hurt.

Tallyboard's InviteService receives email addresses as strings. The invite method trims and lowercases the input, runs a regex, then compares strings to detect duplicates. isExternal trims and lowercases again and splits on @ to read the domain, but it never validates, so a malformed string quietly counts as external.

The normalisation rule now lives in two places, and the domain logic is buried in string slicing. If product decides that +tag suffixes should be stripped, you will have to find every place that handles an email string. Nothing in the type system tells you whether a given string has been cleaned and validated.

Before and after

The same code, before and after the change.

Before

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

interface Invite {
  email: string;
  workspace: string;
}

class InviteService {
  private invites: Invite[] = [];

  constructor(private readonly companyDomain: string) {}

  invite(rawEmail: string, workspace: string): Invite {
    const email = rawEmail.trim().toLowerCase();
    if (!EMAIL_PATTERN.test(email)) {
      throw new Error(`Invalid email: ${rawEmail}`);
    }
    if (this.invites.some((i) => i.email === email && i.workspace === workspace)) {
      throw new Error(`${email} is already invited to ${workspace}`);
    }
    const invite: Invite = { email, workspace };
    this.invites.push(invite);
    return invite;
  }

  isExternal(email: string): boolean {
    const domain = email.trim().toLowerCase().split("@")[1];
    return domain !== this.companyDomain;
  }
}

const service = new InviteService("tallyboard.io");
const invite = service.invite("  Mira.Okafor@Tallyboard.io ", "roadmap");
console.log(invite.email, service.isExternal(invite.email)); // mira.okafor@tallyboard.io false

After

class EmailAddress {
  private static readonly PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  private constructor(private readonly value: string) {}

  static parse(raw: string): EmailAddress {
    const value = raw.trim().toLowerCase();
    if (!EmailAddress.PATTERN.test(value)) {
      throw new Error(`Invalid email: ${raw}`);
    }
    return new EmailAddress(value);
  }

  get domain(): string {
    return this.value.slice(this.value.indexOf("@") + 1);
  }

  equals(other: EmailAddress): boolean {
    return this.value === other.value;
  }

  toString(): string {
    return this.value;
  }
}

interface Invite {
  email: EmailAddress;
  workspace: string;
}

class InviteService {
  private invites: Invite[] = [];

  constructor(private readonly companyDomain: string) {}

  invite(rawEmail: string, workspace: string): Invite {
    const email = EmailAddress.parse(rawEmail);
    if (this.invites.some((i) => i.email.equals(email) && i.workspace === workspace)) {
      throw new Error(`${email} is already invited to ${workspace}`);
    }
    const invite: Invite = { email, workspace };
    this.invites.push(invite);
    return invite;
  }

  isExternal(email: EmailAddress): boolean {
    return email.domain !== this.companyDomain;
  }
}

const service = new InviteService("tallyboard.io");
const invite = service.invite("  Mira.Okafor@Tallyboard.io ", "roadmap");
console.log(String(invite.email), service.isExternal(invite.email)); // mira.okafor@tallyboard.io false

Why it's worth it

What the change buys you.

Once EmailAddress exists, there is exactly one way to get an email into the system: parse. Every instance you hold is already trimmed, lowercased and validated, so downstream code stops re-checking and stops guessing. The constructor is private in TypeScript and PHP, which makes it impossible to skip the rules by accident.

The type also gives the rules a name and a home. Reading the domain becomes email.domain instead of a split and an index, equality becomes equals instead of trusting that both strings were normalised the same way, and the next rule change, such as stripping +tag suffixes, is a one-line edit in parse.

Signatures become self-documenting. isExternal(email: EmailAddress) tells callers they must hand over a validated address, and the compiler or type checker enforces it. The external behaviour of invite is unchanged: same normalisation, same error messages, same duplicate detection.

  • Validation and normalisation run once, at the boundary, instead of at every use.
  • Function signatures state that they need a validated email, and the type checker enforces it.
  • Rule changes such as tag stripping or domain allow-lists happen in one class.
  • Domain logic like reading the email domain reads as intent rather than string slicing.
  • Invalid addresses can no longer slip into code paths that never validated them, such as the old isExternal.

Careful with

  • Changing a public signature from string to EmailAddress breaks every caller. In a large codebase, add an overload or a temporary string-accepting wrapper and migrate gradually.
  • Make sure equality works by value. In Python a frozen dataclass handles this; in TypeScript and PHP you must call equals, because === compares object identity.
  • Serialisation boundaries such as JSON responses, ORMs and query builders still need plain strings. Convert explicitly at those edges rather than leaking the object into storage formats.
  • Do not wrap every string. A primitive earns its own type when it carries rules or behaviour; a free-text note with no constraints usually does not.

Step by step

Small, safe steps, with the tests passing after each.

  1. Pin the current behaviour with tests: a valid invite with messy casing and spaces, an invalid address, a duplicate invite, and isExternal for an internal and an external address.

  2. Create EmailAddress with a parse factory that copies the trim, lowercase and regex check from invite, plus toString (or __str__ / __toString). Add unit tests for it. Nothing uses it yet.

  3. Inside invite, replace the inline normalisation and regex with EmailAddress.parse(rawEmail), then immediately convert back to a string for the rest of the method. Run the tests.

  4. Change the email field of Invite to EmailAddress, remove the temporary string conversion, and switch the duplicate check to equals. Fix any callers that read invite.email as a string by calling toString. Run the tests.

  5. Add a domain accessor to EmailAddress and test it against a few addresses.

  6. Change isExternal to accept an EmailAddress and use domain. Update each caller to pass a parsed value, one call site at a time, running the tests after each.

  7. Delete the old module-level EMAIL_PATTERN constant and any leftover string normalisation once nothing references it. Run the full suite.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

How is this different from Introduce Parameter Object?

Introduce Parameter Object groups several values that travel together, like a start and end date. Replace Primitive with Object wraps a single value that has rules of its own. They often combine: a money amount and its currency code become one Money object, which merges both ideas.

Does wrapping a string in a class hurt performance?

There is one extra small allocation per value, which is negligible for typical request handling. If you are processing millions of values in a tight loop, measure first, but in most business code the cost of a bug from an unvalidated value is far higher.

Why use a static parse method instead of a public constructor?

A named factory makes the validation obvious at the call site and lets you keep the constructor private, so no one can create an instance that skipped the checks. It also leaves room for a second factory later, for example one that trusts already-validated data loaded from your own database.

How would I talk about this refactoring in an interview?

Name the smell, primitive obsession, and point to the symptom: the same validation repeated, or a function that forgot it. Then explain that you moved the rules into a type created through one entry point, and stress that you did it in small steps with tests passing after each change.

Should the value object be immutable?

Yes. If an EmailAddress could change after creation, you would lose the guarantee that it is valid, and two invites sharing the same instance could change together unexpectedly. Make the field readonly or frozen and return new instances for any transformation.