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–10Python bonus
Step 11Recap
Steps 12–13The code: before and after
Before
class AccountService:
def __init__(self) -> None:
self._email_by_id: dict[str, str] = {}
def register(self, customer_id: str, email: str) -> None:
if "@" not in email:
raise ValueError(email)
self._email_by_id[customer_id] = email.lower()
def change_email(self, customer_id: str, new_email: str) -> None:
if "@" not in new_email:
raise ValueError(new_email)
self._email_by_id[customer_id] = new_email
def find_customer(self, email: str) -> str | None:
wanted = email.lower()
for customer_id, stored in self._email_by_id.items():
if stored == wanted:
return customer_id
return None
class SignupController:
def __init__(self, accounts: AccountService) -> None:
self._accounts = accounts
def on_signup(self, email: str, customer_id: str) -> None:
self._accounts.register(customer_id, email)
def support_desk(accounts: AccountService) -> None:
accounts.register("c1", "ana@shop.com")
accounts.change_email("c1", "Ana@Shop.com")
accounts.find_customer("ana@shop.com")After
@dataclass(frozen=True)
class EmailAddress:
value: str
def __post_init__(self) -> None:
if "@" not in self.value:
raise ValueError(self.value)
if "." not in self.value.partition("@")[2]:
raise ValueError(self.value)
object.__setattr__(self, "value", self.value.strip().lower())
CustomerId = NewType("CustomerId", str)
class AccountService:
def __init__(self) -> None:
self._email_by_id: dict[CustomerId, EmailAddress] = {}
def register(self, customer_id: CustomerId, email: EmailAddress) -> None:
self._email_by_id[customer_id] = email
def change_email(
self, customer_id: CustomerId, new_email: EmailAddress
) -> None:
self._email_by_id[customer_id] = new_email
def find_customer(self, email: EmailAddress) -> CustomerId | None:
for customer_id, stored in self._email_by_id.items():
if stored == email:
return customer_id
return None
class SignupController:
def __init__(self, accounts: AccountService) -> None:
self._accounts = accounts
def on_signup(self, email: str, customer_id: str) -> None:
self._accounts.register(CustomerId(customer_id), EmailAddress(email))
def support_desk(accounts: AccountService) -> None:
c1 = CustomerId("c1")
accounts.register(c1, EmailAddress("ana@shop.com"))
accounts.change_email(c1, EmailAddress("Ana@Shop.com"))
accounts.find_customer(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 dict, 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 returns the ID whose stored email matches. The signup controller hands a new customer's email and ID to register. And the support desk function 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 returns None. The customer ID and the email are both strings, so mypy 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 frozen dataclass called Email Address that holds one string value. Register, change email and find customer take an Email Address now, and the dict 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 post init, which the dataclass calls every time an Email Address is built. 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 return None, and now it raises a value error 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 post init too. The dataclass is frozen, so the constructor writes the lowercased value through object set attr, which is the usual way to do that. Register stores the address it's given, and find customer compares two Email Addresses with equals. A dataclass compares its fields, 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 frozen dataclass called Customer ID. The dict, 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, mypy reports an error before the code runs, though Python itself would still run the call.
Payoff
Step 9: Trim and dot, one edit Payoff
Now the trim and the dot rule go back in. Post init checks for an at sign and a dot after it, then stores the value stripped and lowercased. 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 mypy won't let the customer ID and the email trade places, because it knows which one is which.
Python bonus
Step 11: NewType for a rule-free ID Python bonus
Customer ID was a whole dataclass with no rule in it, and its only job was to keep an ID apart from an email. Python's New Type gives mypy the same difference in one line, and at run time a Customer ID is the plain string. The calls don't change, so the signup controller and the support desk still wrap their IDs the same way. New Type can't hold a check, so it only fits a value with no rules, and Email Address stays a dataclass because it owns the email rule.
Recap
Step 12: 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 post init, and Customer ID gives the ID a type of its own. The account service only stores and looks up addresses now.
Step 13: 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. Python already does this with time delta, which carries its unit, so nobody has to guess whether a float means seconds or milliseconds.