Techniquecore
Replace primitive with object
Also called Replace Data Value with Object, Replace Type Code with Class, value object.
Wrap a string or a number that stands for a concept of the domain, such as an email address or an amount of money, in a small class that holds the rules of that concept.
- Family
- refactoring
- Intent
- Give a value of the domain its own type, so that its rules have one home.
- Also called
- Replace Data Value with Object, Replace Type Code with Class
Purpose
Early in a program, a fact is often a plain value: a string for an email address, a number for a price, a string such as high for a priority. That is the right first choice. Later the value gathers rules. Emails compare without regard to case; a price has a currency; priorities have an order. With a plain value, each rule is written again at each place that needs it.1
Replace primitive with object makes a small class for the value. At first the class only wraps the value, but it is a place to put the rules, and the rules then move in from the callers.1 The catalogue card shows a filter that compares o.priority with the strings high and rush becoming a filter that calls o.priority.higherThan(...) with a Priority object for normal.2 The card lists two first-edition names, Replace Data Value with Object and Replace Type Code with Class, which the first edition had as separate refactorings.23
The class is usually a value object. Fowler defines value objects as "Objects that are equal due to the value of their properties", and says that "value objects should be immutable".4
Steps
- Run the tests and see them pass.
- If the variable is not yet behind accessors, apply Encapsulate Variable.1
- Write a value class. Its constructor takes the primitive value, and it has a getter for it.
- Run the static checks.
- Change the setter to make an instance of the class and store it in the field. Change the getter to return the primitive from the instance. Test.
- Consider renaming the accessors, with Change Function Declaration, so that they say what they return.
- Move each rule about the value from its callers into the class, and test after each.
- Decide whether the object is a value, compared by its contents, or a reference, with one shared instance per thing.1
Example
User accounts store email addresses as strings, and the code lowercases them in each place that compares them. After the refactoring, an Email class checks the value once, compares by value and answers the question about the domain.
import assert from "node:assert/strict";
// Before: the rules are repeated wherever an email is used.
const sameUserBefore = (a, b) => a.trim().toLowerCase() === b.trim().toLowerCase();
const isStaffBefore = (e) => e.trim().toLowerCase().endsWith("@example.org");
// After: a value object. It is checked once, frozen, and compared by value.
class Email {
#value;
constructor(text) {
const v = String(text).trim().toLowerCase();
if (!/^[^@\s]+@[^@\s]+$/.test(v)) throw new TypeError(`not an email: ${text}`);
this.#value = v;
Object.freeze(this);
}
get domain() { return this.#value.slice(this.#value.indexOf("@") + 1); }
equals(other) { return other instanceof Email && other.#value === this.#value; }
toString() { return this.#value; }
}
const sameUser = (a, b) => a.equals(b);
const isStaff = (e) => e.domain === "example.org";
const pairs = [[" Ana@Example.org", "ana@example.org"], ["bo@x.io", "Bo@Y.io"]];
for (const [a, b] of pairs) {
assert.equal(sameUser(new Email(a), new Email(b)), sameUserBefore(a, b));
}
assert.equal(isStaff(new Email("Cy@EXAMPLE.org")), isStaffBefore("Cy@EXAMPLE.org"));
// A bad value fails where it enters, not later where it is used.
assert.throws(() => new Email("not-an-email"), TypeError);
// JavaScript compares objects by reference, so equals is needed.
assert.notEqual(new Email("a@b.c"), new Email("a@b.c"));
console.log("replace primitive with object: tests pass");
replace primitive with object: tests pass
The rule for comparing emails now lives in one place. The last line shows a trap that the bliki describes: JavaScript "tests equality for js objects by looking at their references, ignoring the values they contain", so a value class needs its own equals.4
| Language | What the example shows |
|---|---|
| JavaScript | an Email class with a check, equals and a derived domain, as above |
| Python | a frozen dataclass, which compares by value with no extra code |
| Java | a record, which compares by value and checks in its compact constructor |
| Go | a named type type Email string with methods, the lightest form of the refactoring |
import re
from dataclasses import dataclass
@dataclass(frozen=True)
class Email:
value: str
def __post_init__(self):
v = self.value.strip().lower()
if not re.fullmatch(r"[^@\s]+@[^@\s]+", v):
raise ValueError(f"not an email: {self.value!r}")
object.__setattr__(self, "value", v) # normalize once, in a frozen class
@property
def domain(self):
return self.value.split("@", 1)[1]
# The dataclass generates __eq__ and __hash__ from the fields.
assert Email(" Ana@Example.org") == Email("ana@example.org")
assert Email("Cy@EXAMPLE.org").domain == "example.org"
assert len({Email("a@b.c"), Email("A@B.C")}) == 1 # usable as a set member
try:
Email("not-an-email")
raise AssertionError("expected a ValueError")
except ValueError as e:
print(e)
print("replace primitive with object: tests pass")
not an email: 'not-an-email'
replace primitive with object: tests pass
import java.util.Locale;
import java.util.Set;
public class Main {
// A record compares by value. The compact constructor checks and normalizes.
record Email(String value) {
Email {
value = value.strip().toLowerCase(Locale.ROOT);
if (!value.matches("[^@\\s]+@[^@\\s]+")) throw new IllegalArgumentException("not an email: " + value);
}
String domain() { return value.substring(value.indexOf('@') + 1); }
}
public static void main(String[] args) {
Email a = new Email(" Ana@Example.org");
Email b = new Email("ana@example.org");
if (!a.equals(b) || a == b) throw new AssertionError("expected equal values, distinct objects");
if (!new Email("Cy@EXAMPLE.org").domain().equals("example.org")) throw new AssertionError("domain");
if (Set.of(a).size() != 1 || !Set.of(a).contains(b)) throw new AssertionError("hashCode");
try {
new Email("not-an-email");
throw new AssertionError("expected an exception");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
System.out.println(a);
System.out.println("replace primitive with object: tests pass");
}
}
not an email: not-an-email
Email[value=ana@example.org]
replace primitive with object: tests pass
package main
import (
"fmt"
"strings"
)
// A named type is the lightest form: no wrapper struct, but its own
// methods, and the compiler stops a plain UserID from being passed as an Email.
type Email string
type UserID string
func ParseEmail(s string) (Email, error) {
v := strings.ToLower(strings.TrimSpace(s))
at := strings.IndexByte(v, '@')
if at <= 0 || at != strings.LastIndexByte(v, '@') || at == len(v)-1 {
return "", fmt.Errorf("not an email: %q", s)
}
return Email(v), nil
}
func (e Email) Domain() string { return string(e[strings.IndexByte(string(e), '@')+1:]) }
func notify(to Email) string { return "mail to " + string(to) }
func main() {
a, _ := ParseEmail(" Ana@Example.org")
b, _ := ParseEmail("ana@example.org")
fmt.Println(a == b, a.Domain(), notify(a)) // == compares the values
var id UserID = "u-17"
_ = id // notify(id) does not compile: cannot use id (UserID) as Email
if _, err := ParseEmail("not-an-email"); err != nil {
fmt.Println(err)
}
fmt.Println("replace primitive with object: tests pass")
}
true example.org mail to ana@example.org
not an email: "not-an-email"
replace primitive with object: tests pass
When to use
- A primitive has rules. Formatting, parsing, comparison, validation or arithmetic that is repeated at each use. This is the smell Primitive Obsession, and the book names this refactoring as a fix for it.1
- A string stands for one of a fixed set of values. A priority, a status, a type code. The class can give the order and the allowed values. If the values select behaviour, the next step is to replace the conditionals with subclasses or polymorphism.
- Two values travel together. An amount and a currency is one concept. That is also Data Clumps, and Introduce Parameter Object is the related fix.
Pitfalls
Equality by reference. In JavaScript and in Java classes, == or === on two objects compares references. A value class needs an equals method, or a language form that compares by value. Java records and Python dataclasses generate the comparison.56
A mutable value. If two accounts share one Email object and one changes it, both change. Make value classes immutable, as the bliki advises.4 A Python dataclass with frozen=True emulates immutability.6
A wrapper with no rules. A class that only wraps a string adds a type and costs a little code at each boundary. The gain is in the check and the rules; if there are none yet, the wrapper is still useful when it stops two kinds of string, such as a user ID and an order ID, from being mixed up.
The boundary. Databases, JSON and HTTP carry primitives. Convert at the edge of the program, and use the value class inside it.
Tools that do it
This refactoring is a sequence of steps, not one action of a tool. A tool can generate the class, a record type or a dataclass; the move of each rule from its callers into the class is the programmer's step, with a test after each.
References
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 7, Encapsulation, Replace Primitive with Object, motivation and mechanics; Chapter 3, Bad Smells in Code, Primitive Obsession
- Martin Fowler, Catalog of Refactorings, Replace Primitive with Object, the entry; aliases Replace Data Value with Object, Replace Type Code with Class
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 8, Organizing Data, Replace Data Value with Object and Replace Type Code with Class
- Martin Fowler, Value Object, bliki, the definition and the note on immutability
- JEP 395, Records, Summary, and the standard members that a record class acquires automatically
- Python documentation, dataclasses, Data Classes, frozen instances
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag ZY7MSK Edit this page History Report an error Markdown