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 falseimport re
from dataclasses import dataclass
EMAIL_PATTERN = re.compile(r"[^\s@]+@[^\s@]+\.[^\s@]+")
@dataclass(frozen=True)
class Invite:
email: str
workspace: str
class InviteService:
def __init__(self, company_domain: str) -> None:
self.company_domain = company_domain
self.invites: list[Invite] = []
def invite(self, raw_email: str, workspace: str) -> Invite:
email = raw_email.strip().lower()
if not EMAIL_PATTERN.fullmatch(email):
raise ValueError(f"Invalid email: {raw_email}")
if any(i.email == email and i.workspace == workspace for i in self.invites):
raise ValueError(f"{email} is already invited to {workspace}")
invite = Invite(email, workspace)
self.invites.append(invite)
return invite
def is_external(self, email: str) -> bool:
domain = email.strip().lower().split("@")[1]
return domain != self.company_domain
service = InviteService("tallyboard.io")
invite = service.invite(" Mira.Okafor@Tallyboard.io ", "roadmap")
print(invite.email, service.is_external(invite.email)) # mira.okafor@tallyboard.io False<?php
final class Invite
{
public function __construct(
public readonly string $email,
public readonly string $workspace,
) {}
}
final class InviteService
{
private const EMAIL_PATTERN = '/^[^\s@]+@[^\s@]+\.[^\s@]+$/D';
/** @var Invite[] */
private array $invites = [];
public function __construct(private readonly string $companyDomain) {}
public function invite(string $rawEmail, string $workspace): Invite
{
$email = strtolower(trim($rawEmail));
if (preg_match(self::EMAIL_PATTERN, $email) !== 1) {
throw new InvalidArgumentException("Invalid email: {$rawEmail}");
}
foreach ($this->invites as $existing) {
if ($existing->email === $email && $existing->workspace === $workspace) {
throw new DomainException("{$email} is already invited to {$workspace}");
}
}
$invite = new Invite($email, $workspace);
$this->invites[] = $invite;
return $invite;
}
public function isExternal(string $email): bool
{
$domain = explode('@', strtolower(trim($email)))[1] ?? '';
return $domain !== $this->companyDomain;
}
}
$service = new InviteService('tallyboard.io');
$invite = $service->invite(' Mira.Okafor@Tallyboard.io ', 'roadmap');
echo $invite->email, ' ', var_export($service->isExternal($invite->email), true), PHP_EOL;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 falseimport re
from dataclasses import dataclass
@dataclass(frozen=True)
class EmailAddress:
value: str
_PATTERN = re.compile(r"[^\s@]+@[^\s@]+\.[^\s@]+")
@classmethod
def parse(cls, raw: str) -> "EmailAddress":
value = raw.strip().lower()
if not cls._PATTERN.fullmatch(value):
raise ValueError(f"Invalid email: {raw}")
return cls(value)
@property
def domain(self) -> str:
return self.value.split("@")[1]
def __str__(self) -> str:
return self.value
@dataclass(frozen=True)
class Invite:
email: EmailAddress
workspace: str
class InviteService:
def __init__(self, company_domain: str) -> None:
self.company_domain = company_domain
self.invites: list[Invite] = []
def invite(self, raw_email: str, workspace: str) -> Invite:
email = EmailAddress.parse(raw_email)
if any(i.email == email and i.workspace == workspace for i in self.invites):
raise ValueError(f"{email} is already invited to {workspace}")
invite = Invite(email, workspace)
self.invites.append(invite)
return invite
def is_external(self, email: EmailAddress) -> bool:
return email.domain != self.company_domain
service = InviteService("tallyboard.io")
invite = service.invite(" Mira.Okafor@Tallyboard.io ", "roadmap")
print(invite.email, service.is_external(invite.email)) # mira.okafor@tallyboard.io False<?php
final class EmailAddress
{
private const PATTERN = '/^[^\s@]+@[^\s@]+\.[^\s@]+$/D';
private function __construct(private readonly string $value) {}
public static function parse(string $raw): self
{
$value = strtolower(trim($raw));
if (preg_match(self::PATTERN, $value) !== 1) {
throw new InvalidArgumentException("Invalid email: {$raw}");
}
return new self($value);
}
public function domain(): string
{
return substr($this->value, strpos($this->value, '@') + 1);
}
public function equals(self $other): bool
{
return $this->value === $other->value;
}
public function __toString(): string
{
return $this->value;
}
}
final class Invite
{
public function __construct(
public readonly EmailAddress $email,
public readonly string $workspace,
) {}
}
final class InviteService
{
/** @var Invite[] */
private array $invites = [];
public function __construct(private readonly string $companyDomain) {}
public function invite(string $rawEmail, string $workspace): Invite
{
$email = EmailAddress::parse($rawEmail);
foreach ($this->invites as $existing) {
if ($existing->email->equals($email) && $existing->workspace === $workspace) {
throw new DomainException("{$email} is already invited to {$workspace}");
}
}
$invite = new Invite($email, $workspace);
$this->invites[] = $invite;
return $invite;
}
public function isExternal(EmailAddress $email): bool
{
return $email->domain() !== $this->companyDomain;
}
}
$service = new InviteService('tallyboard.io');
$invite = $service->invite(' Mira.Okafor@Tallyboard.io ', 'roadmap');
echo $invite->email, ' ', var_export($service->isExternal($invite->email), true), PHP_EOL;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
stringtoEmailAddressbreaks 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.
Pin the current behaviour with tests: a valid invite with messy casing and spaces, an invalid address, a duplicate invite, and
isExternalfor an internal and an external address.Create
EmailAddresswith aparsefactory that copies the trim, lowercase and regex check frominvite, plustoString(or__str__/__toString). Add unit tests for it. Nothing uses it yet.Inside
invite, replace the inline normalisation and regex withEmailAddress.parse(rawEmail), then immediately convert back to a string for the rest of the method. Run the tests.Change the
emailfield ofInvitetoEmailAddress, remove the temporary string conversion, and switch the duplicate check toequals. Fix any callers that readinvite.emailas a string by callingtoString. Run the tests.Add a
domainaccessor toEmailAddressand test it against a few addresses.Change
isExternalto accept anEmailAddressand usedomain. Update each caller to pass a parsed value, one call site at a time, running the tests after each.Delete the old module-level
EMAIL_PATTERNconstant 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.