Primitive obsession: introduce domain types
Give a value its own type, so its rules live in one place.
Watch the narrated video
Every step
Problem
Steps 1–4Refactor
Steps 5–8Payoff
Steps 9–10Recap
Steps 11–12The code: before and after
Before
class AccountService
{
private readonly Dictionary<string, string> emailById = new();
public void Register(string customerId, string email)
{
if (!email.Contains('@'))
throw new ArgumentException(email);
emailById[customerId] = email.ToLowerInvariant();
}
public void ChangeEmail(string customerId, string newEmail)
{
if (!newEmail.Contains('@'))
throw new ArgumentException(newEmail);
emailById[customerId] = newEmail;
}
public string? FindCustomer(string email)
{
string wanted = email.ToLowerInvariant();
return emailById.Where(e => e.Value == wanted)
.Select(e => e.Key)
.FirstOrDefault();
}
}
class SignupController(AccountService accounts)
{
public void OnSignup(string email, string customerId)
{
accounts.Register(customerId, email);
}
}
static class SupportDesk
{
public static void Run(AccountService accounts)
{
accounts.Register("c1", "ana@shop.com");
accounts.ChangeEmail("c1", "Ana@Shop.com");
accounts.FindCustomer("ana@shop.com");
}
}After
record EmailAddress
{
public string Value { get; }
public EmailAddress(string value)
{
value = value.Trim();
if (!value.Contains('@'))
throw new ArgumentException(value);
if (value.IndexOf('.', value.IndexOf('@')) < 0)
throw new ArgumentException(value);
Value = value.ToLowerInvariant();
}
}
record CustomerId(string Value);
class AccountService
{
private readonly Dictionary<CustomerId, EmailAddress> emailById = new();
public void Register(CustomerId customerId, EmailAddress email)
{
emailById[customerId] = email;
}
public void ChangeEmail(CustomerId customerId, EmailAddress newEmail)
{
emailById[customerId] = newEmail;
}
public CustomerId? FindCustomer(EmailAddress email)
{
return emailById.Where(e => e.Value == email)
.Select(e => e.Key)
.FirstOrDefault();
}
}
class SignupController(AccountService accounts)
{
public void OnSignup(string email, string customerId)
{
accounts.Register(new CustomerId(customerId),
new EmailAddress(email));
}
}
static class SupportDesk
{
public static void Run(AccountService accounts)
{
var c1 = new CustomerId("c1");
accounts.Register(c1, new EmailAddress("ana@shop.com"));
accounts.ChangeEmail(c1, new EmailAddress("Ana@Shop.com"));
accounts.FindCustomer(new EmailAddress("ana@shop.com"));
}
}Transcript, step by step
Problem
Step 1: Accounts keyed by strings Before
This account service keeps every customer's email in a dictionary, keyed by customer ID. Register checks that the address has an at sign and stores it in lower case, and change email checks it too. Find customer lowercases the address you ask for and looks for a matching email in the dictionary. The signup controller hands a new customer's email and ID to register. And the support desk registers Ana, changes her email, then looks her up by address.
Step 2: Trim it, three times Code smell
Support says customers paste emails with spaces around them, so trim them, and reject an address with no dot after the at sign. Primitive obsession is using a plain string for an idea that has its own rules, so every method that touches the string must remember them. You can see it here in register, here in change email, and here in find customer. Each of them had to learn the new rule, and the next rule about emails will cost the same three edits.
Step 3: Already drifted Code smell
And the copies have already drifted, because change email stores the address without lowercasing it. So when the support desk changes Ana's email to a capitalized address, the lookup in lower case comes back null. The customer ID and the email are both strings, so the compiler accepts them in either order. Look at the signup call, which takes the email first and hands it to register, which wants the ID first. Swap them by mistake, and nothing fails until a lookup returns the wrong customer.
Step 4: Back it out, then add types Plan
Let's back that change out. First the email and the customer ID get types of their own, so the email rule has one home, and then the trim and the dot check go in there.
Refactor
Step 5: The email gets a type Replace Primitive with Object
We start with the email, as a record called Email Address that holds one string value. We write its constructor out in full, because that's where the email rule is going to move. Register, change email and find customer take an Email Address now, and the dictionary stores them too. The checks stay where they were for now, and they read the string through Value. The signup controller and the support desk wrap their strings at the call, so the program does the same as before.
Step 6: The @ check moves in Move Statements into Function
The at sign check was the same in both methods, so it moves into the record's constructor. Register and change email lose their checks, and an address without an at sign can't even be built. One more thing changes here, because a lookup for an invalid address like bob used to come back null, and now it throws when its Email Address is built.
Step 7: Lowercase moves in Move Statements into Function
Lowercasing is the other half of the email rule, so it moves into the constructor too. Register stores the address it's given, and find customer compares two Email Addresses with the equals operator. A record compares its values, so two addresses with the same text are equal, which makes Email Address a value object. This step changes one behavior on purpose, because change email now stores a lowercased address too, and that fixes the drift. So the support desk's lookup finds Ana's ID again.
Step 8: The ID gets a type Replace Primitive with Object
The customer ID gets the same treatment, as a record called Customer ID. The dictionary, register, change email and the result of find customer all use it. The signup controller builds both types, and the support desk names its customer once. Now if you swap the two arguments, the code doesn't compile, because an Email Address is not a Customer ID.
Payoff
Step 9: Trim and dot, one edit Payoff
Now the trim and the dot rule go back in. The constructor trims the value first, then checks for an at sign and a dot after it, and lowercases last. The account service and the signup controller didn't change. Register, change email and find customer hold no email rule now, and the support desk's calls find Ana's ID again.
Step 10: Why the types paid off Payoff
The email rule used to live in three methods and had already drifted, so now one constructor owns it. A method can't forget the rule, because every Email Address it receives went through that constructor. And the customer ID and the email can't trade places, because the compiler knows which one is which.
Recap
Step 11: Where we started, where we ended Before / after
On the left, every method took two strings, and the customer ID and the email could trade places. The at sign check was written twice, and the lowercase was in register and find customer but missing from change email. On the right, Email Address owns the whole rule in its constructor, and Customer ID gives the ID a type of its own. The account service only stores and looks up addresses now.
Step 12: When to reach for it Takeaways
Reach for a domain type when a value has rules that more than one method checks, or when two values of the same type are easy to swap. Skip it for a string with no rules that passes through once, like a delivery note, because a wrapper adds a type and gives you nothing back. You'll spot it by the same check repeated across methods, several strings in one signature, and names that carry the format. C sharp already does this with Time Span, which carries its unit, so nobody has to guess whether an int means seconds or milliseconds.