Programming Search⌘K

Patterncore

Primitive Obsession

Also called stringly typed code.

A code smell: a domain value, such as an amount of money or a phone number, is kept in a plain number or string, so its rules are spread through the code and the compiler cannot tell it apart.

Family
code-smell
Intent
Find the domain values that live in primitive types, and give each one a small type that holds its rules and that the compiler can tell apart from other values.

Intent

Find the values of the problem domain that the program keeps in primitive types, such as numbers and strings, and give each one a small type of its own. The type holds the rules about the value, and the compiler or the type checker can then tell an amount of money from a count, or a user ID from an order ID.

Problem

Every language gives a set of primitive types: integers, floating point numbers, strings and booleans. A program also deals with values that are more than that: an amount of money, a phone number, a temperature, a postcode. Refactoring says that programmers are often slow to make small types for such values, and use a number for money and a string for a phone number.1 It also names the extreme form, code where many values are strings, which it calls stringly typed.1

The forces are these:

  • A primitive is always there and costs nothing to write. A class for money seems like too much work for a value that fits in one integer.
  • The rules for the value have no home. The check that a postcode has the right form, the rounding of money and the format for display are written again wherever they are needed, and the copies drift apart.
  • Two values of the same primitive type are interchangeable to the compiler. A function that takes a price in cents and a quantity, both integers, accepts them in either order.
  • A value with a unit, such as money with a currency or a length in metres, loses the unit when it is a plain number. Code that adds two such numbers cannot know if the units match.
  • A type code, such as a string "admin" or "guest", is a primitive that stands for a kind of thing. The code that depends on the kind becomes a switch on the string in each place.

Solution

Refactoring names a refactoring for each form of the smell.1 The catalogue at refactoring.com has a card for each one, and gives Replace Data Value with Object and Replace Type Code with Class as other names for Replace Primitive with Object.2

  1. A single value with rules: Replace Primitive with Object. Make a small class for the value, and move the checks, the formatting and the arithmetic into it.
  2. A type code that controls behaviour: Replace Type Code with Subclasses, then Replace Conditional with Polymorphism to move each branch of the switch into a subclass.
  3. A group of primitives that always appear together: Extract Class and Introduce Parameter Object. Fowler notes that "Often data clumps are primitive values that nobody thinks to turn into an object."3 See Data Clumps.

Most languages give a cheap way to make a distinct type from a primitive:

  • In Go, a type definition creates "a defined type. It is different from any other type, including the type it is created from."4 A type Cents int64 can have methods, and a plain int64 variable cannot be passed where Cents is expected without a conversion.
  • In Python, NewType creates "distinct types" for a static type checker. The documentation adds that "these checks are enforced only by the static type checker", and that at runtime the call "returns its argument unchanged."5
  • In Rust, a thin wrapper of an existing type in another struct "is known as the newtype pattern", and the wrapper is a tuple struct with one field. The Rust book says that "There is no runtime performance penalty for using this pattern, and the wrapper type is elided at compile time."6
  • In Java, a record class is "a restricted kind of class" for an aggregate of values, and gets its constructor, accessors, equals and hashCode from its components.7

Example

An order has lines, and each line has a price in cents and a currency code as a string. The total adds up the cents. When a line in another currency gets into the order, the total is a number with no meaning, and no code notices.

import assert from "node:assert/strict";

// Before: money is a number of cents and a separate string.
function totalBefore(lines) {
  return lines.reduce((sum, line) => sum + line.cents, 0);
}
const formatBefore = (cents, currency) => `${(cents / 100).toFixed(2)} ${currency}`;

const lines = [
  { cents: 1250, currency: "EUR" },
  { cents: 800, currency: "EUR" },
  { cents: 500, currency: "USD" },
];
assert.equal(formatBefore(totalBefore(lines), "EUR"), "25.50 EUR"); // 5 dollars counted as 5 euros
console.log("before: the total mixes two currencies");

// After: Money holds the amount, the currency and the rules.
class Money {
  constructor(cents, currency) {
    if (!Number.isInteger(cents)) throw new TypeError(`cents must be an integer: ${cents}`);
    if (!/^[A-Z]{3}$/.test(currency)) throw new RangeError(`currency code ${currency}`);
    this.cents = cents;
    this.currency = currency;
    Object.freeze(this);
  }
  add(other) {
    if (other.currency !== this.currency) {
      throw new RangeError(`cannot add ${other.currency} to ${this.currency}`);
    }
    return new Money(this.cents + other.cents, this.currency);
  }
  toString() {
    return `${(this.cents / 100).toFixed(2)} ${this.currency}`;
  }
}

const total = (prices) => prices.reduce((sum, price) => sum.add(price));

const euros = [new Money(1250, "EUR"), new Money(800, "EUR")];
assert.equal(total(euros).toString(), "20.50 EUR");
assert.throws(() => total([...euros, new Money(500, "USD")]), RangeError);
assert.throws(() => new Money(12.5, "EUR"), TypeError);
assert.throws(() => new Money(100, "euro"), RangeError);
console.log("after: tests pass");
Output
before: the total mixes two currencies
after: tests pass

The second version moves three rules into one class: the amount is a whole number of cents, the currency is a three-letter code, and two amounts add only when their currencies match. The format for display is written once, in toString. The total of the mixed order is now an error at the point where the currencies meet.

Language What the example shows
JavaScript a frozen Money class, as above
Python a frozen dataclass with __add__, and NewType for an ID
Java a record with a compact constructor and a plus method
Go a struct with unexported fields, and a defined type Cents
PythonGitHub
import re
from dataclasses import dataclass
from functools import reduce
from typing import NewType


# Before: money is a number of cents and a separate string.
def total_before(lines):
    return sum(line["cents"] for line in lines)


def format_before(cents, currency):
    return f"{cents / 100:.2f} {currency}"


lines = [
    {"cents": 1250, "currency": "EUR"},
    {"cents": 800, "currency": "EUR"},
    {"cents": 500, "currency": "USD"},
]
assert format_before(total_before(lines), "EUR") == "25.50 EUR"  # 5 dollars counted as 5 euros
print("before: the total mixes two currencies")


# After: Money holds the amount, the currency and the rules.
@dataclass(frozen=True)
class Money:
    cents: int
    currency: str

    def __post_init__(self):
        if not isinstance(self.cents, int):
            raise TypeError(f"cents must be an integer: {self.cents!r}")
        if not re.fullmatch(r"[A-Z]{3}", self.currency):
            raise ValueError(f"currency code {self.currency!r}")

    def __add__(self, other):
        if other.currency != self.currency:
            raise ValueError(f"cannot add {other.currency} to {self.currency}")
        return Money(self.cents + other.cents, self.currency)

    def __str__(self):
        return f"{self.cents / 100:.2f} {self.currency}"


def total(prices):
    return reduce(lambda a, b: a + b, prices)


def raises(exc, f):
    try:
        f()
    except exc:
        return True
    return False


euros = [Money(1250, "EUR"), Money(800, "EUR")]
assert str(total(euros)) == "20.50 EUR"
assert raises(ValueError, lambda: total([*euros, Money(500, "USD")]))
assert raises(TypeError, lambda: Money(12.5, "EUR"))
assert raises(ValueError, lambda: Money(100, "euro"))

# NewType: a distinct type for the type checker, a plain int at runtime.
UserId = NewType("UserId", int)
uid = UserId(42)
assert uid == 42 and type(uid) is int
print("after: tests pass")
Output
before: the total mixes two currencies
after: tests pass
  • __add__ lets the code write a + b for two amounts, and the currency check runs on each addition.
  • NewType costs nothing at runtime, as the last test shows: UserId(42) is the integer 42. A type checker such as mypy reports a call that passes a plain int where a UserId is expected, but Python itself does not.
JavaGitHub
import java.util.List;

public class Main {
    record Line(long cents, String currency) {}

    // Before: money is a number of cents and a separate string.
    static long totalBefore(List<Line> lines) {
        return lines.stream().mapToLong(Line::cents).sum();
    }

    static String formatBefore(long cents, String currency) {
        return String.format("%d.%02d %s", cents / 100, cents % 100, currency);
    }

    // After: Money holds the amount, the currency and the rules.
    record Money(long cents, String currency) {
        Money {
            if (currency == null || !currency.matches("[A-Z]{3}")) {
                throw new IllegalArgumentException("currency code " + currency);
            }
        }

        Money plus(Money other) {
            if (!other.currency.equals(currency)) {
                throw new IllegalArgumentException("cannot add " + other.currency + " to " + currency);
            }
            return new Money(Math.addExact(cents, other.cents), currency);
        }

        @Override
        public String toString() {
            return String.format("%d.%02d %s", cents / 100, cents % 100, currency);
        }
    }

    static Money total(List<Money> prices) {
        return prices.stream().reduce(Money::plus).orElseThrow();
    }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    static boolean rejects(Runnable r) {
        try {
            r.run();
            return false;
        } catch (IllegalArgumentException e) {
            return true;
        }
    }

    public static void main(String[] args) {
        List<Line> lines = List.of(new Line(1250, "EUR"), new Line(800, "EUR"), new Line(500, "USD"));
        check(formatBefore(totalBefore(lines), "EUR").equals("25.50 EUR"), "before"); // 5 dollars as 5 euros
        System.out.println("before: the total mixes two currencies");

        List<Money> euros = List.of(new Money(1250, "EUR"), new Money(800, "EUR"));
        check(total(euros).toString().equals("20.50 EUR"), "total");
        check(rejects(() -> total(List.of(euros.get(0), new Money(500, "USD")))), "mixed currencies");
        check(rejects(() -> new Money(100, "euro")), "bad code");
        check(new Money(100, "EUR").equals(new Money(100, "EUR")), "equal by value");
        System.out.println("after: tests pass");
    }
}
Output
before: the total mixes two currencies
after: tests pass
  • The long type of cents already rules out a fraction of a cent, so the record needs no check for it. Math.addExact throws on overflow in place of a silent wrap.
  • The record gets equals and hashCode from its two components, so two amounts with the same cents and currency are equal.
package main

import (
	"fmt"
	"regexp"
)

type line struct {
	cents    int64
	currency string
}

// Before: money is a number of cents and a separate string.
func totalBefore(lines []line) int64 {
	var sum int64
	for _, l := range lines {
		sum += l.cents
	}
	return sum
}

func formatBefore(cents int64, currency string) string {
	return fmt.Sprintf("%d.%02d %s", cents/100, cents%100, currency)
}

// After: a defined type for the amount, and Money for the amount and its currency.
type Cents int64

type Money struct {
	cents    Cents
	currency string
}

var currencyCode = regexp.MustCompile(`^[A-Z]{3}$`)

func NewMoney(cents Cents, currency string) (Money, error) {
	if !currencyCode.MatchString(currency) {
		return Money{}, fmt.Errorf("currency code %q", currency)
	}
	return Money{cents, currency}, nil
}

func (m Money) Add(other Money) (Money, error) {
	if other.currency != m.currency {
		return Money{}, fmt.Errorf("cannot add %s to %s", other.currency, m.currency)
	}
	return Money{m.cents + other.cents, m.currency}, nil
}

func (m Money) String() string {
	return fmt.Sprintf("%d.%02d %s", m.cents/100, m.cents%100, m.currency)
}

func total(prices []Money) (Money, error) {
	sum := prices[0]
	for _, p := range prices[1:] {
		var err error
		if sum, err = sum.Add(p); err != nil {
			return Money{}, err
		}
	}
	return sum, nil
}

func must(m Money, err error) Money {
	if err != nil {
		panic(err)
	}
	return m
}

func check(ok bool, what string) {
	if !ok {
		panic(what)
	}
}

func main() {
	lines := []line{{1250, "EUR"}, {800, "EUR"}, {500, "USD"}}
	check(formatBefore(totalBefore(lines), "EUR") == "25.50 EUR", "before") // 5 dollars as 5 euros
	fmt.Println("before: the total mixes two currencies")

	euros := []Money{must(NewMoney(1250, "EUR")), must(NewMoney(800, "EUR"))}
	sum, err := total(euros)
	check(err == nil && sum.String() == "20.50 EUR", "total")
	_, err = total(append(euros, must(NewMoney(500, "USD"))))
	check(err != nil, "mixed currencies")
	_, err = NewMoney(100, "euro")
	check(err != nil, "bad code")
	check(must(NewMoney(100, "EUR")) == must(NewMoney(100, "EUR")), "equal by value")
	fmt.Println("after: tests pass")
}
Output
before: the total mixes two currencies
after: tests pass
  • Cents is a defined type, so an int64 variable must be converted with Cents(n) before it can be passed where Cents is expected. An untyped constant, such as 1250, converts without one.
  • Because Money has a String method, fmt.Println(m) and %v print it in the format of the type.

Consequences

The rules about a value are in one place and are tested once. A value that passed the constructor is valid, so the functions that receive it need no checks of their own. Signatures say what they take: charge(Money) is clearer than charge(int, String), and two arguments of different domain types cannot be swapped by mistake.

The type is also a place for behaviour to grow. Refactoring, in the chapter on Replace Primitive with Object, notes that a small class for a value often begins as a wrapper with no behaviour, and becomes useful as functions that need the value move into it.1

The costs are small but real:

  • Each type is more code, and the conversions at the edges of the program, such as reading from a database or writing JSON, must build and take apart the objects.
  • An object for each value can use more memory than a primitive. The Go defined type and the Rust newtype avoid this cost.46 A Python NewType avoids it too, but gives no check at runtime.5
  • A wrapper for every number is its own kind of noise. A loop counter or an index is a primitive and should stay one. The smell is a domain value with rules, not every integer.

How to fix it

Data Clumps. A group of primitives that travels together. The fix for both smells is a small type. See Data Clumps.

Repeated Switches. A type code that is a string or an integer leads to a switch on it in many functions. See Repeated Switches.

Value objects. The small immutable types that replace primitives, compared by their fields. See Value object and Equality and identity.

Mutable Data. A value type is often made immutable, so that it can be shared safely. See Mutable Data.

References

  1. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Primitive Obsession, and Chapter 7, Replace Primitive with Object
  2. Martin Fowler, Catalog of Refactorings, the cards Replace Primitive with Object, Replace Type Code with Subclasses, Replace Conditional with Polymorphism, Extract Class and Introduce Parameter Object
  3. Martin Fowler, Data Clump, bliki, 5 January 2006, the second paragraph
  4. The Go Programming Language Specification, Type definitions
  5. Python documentation, typing, Support for type hints, Python 3.14, NewType
  6. The Rust Programming Language, Advanced Traits, Using Default Generic Type Parameters and Operator Overloading, and Implementing External Traits with the Newtype Pattern
  7. The Java Language Specification, Java SE 25 Edition, Chapter 8, Classes, 8.10 Record Classes
  8. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Primitive Obsession

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/0AEHW0/text.yaml