Primitive Obsession

November 25, 20268 minutes

A number without a unit is a guess. Learn to spot domain values hiding in primitives and give them small types that check once and are refused in the wrong place.

In the late nineties, NASA sent an orbiter to Mars. As it arrived, it flew far lower than planned, and it was lost. The investigation traced it to one number that couldn’t say what it measured. In code, keeping values like that in raw numbers and strings is a smell called Primitive Obsession.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

A number without a unit

Mars Climate Orbiter was lost on 23 September 1999. According to NASA’s Mishap Investigation Board, ground software supplied by Lockheed Martin wrote thruster impulse in pound-force seconds; the navigation software read it as newton-seconds, which is what the interface specification required. The thruster effects it worked out were off by a factor of about 4.45. The orbiter was meant to pass about 226 km above Mars; it went to roughly 57 km and was lost.

NASA also blamed the checks that should have caught it. But at the root was a number that couldn’t say what it measured.

Ground software wrote an impulse value in pound-force seconds; the navigation software read the same number as newton-seconds. The number was right, the unit was not, and the trajectory was off by a factor of 4.45. Ground software wrote an impulse value in pound-force seconds; the navigation software read the same number as newton-seconds. The number was right, the unit was not, and the trajectory was off by a factor of 4.45.
The numbers were right. The units were not.

A number without a unit is a guess.

The note and the passport

Here’s a sticky note. It says: Maria, citizen, 5. Who checked it? Five what? Is any of it true? Anyone can write anything on a note, so everyone who reads it has to check it again, in their own way.

A passport is different. It was checked once, when it was issued. It says exactly what it is, and it knows when it expires. And a border officer won’t take your library card instead, even though it has a number on it too.

Keeping domain values in raw doubles, ints and strings is writing them on sticky notes. Fowler and Beck note how reluctant programmers are to make small types of their own (paraphrased).

The analogy mapped onto code. A sticky note is a raw primitive such as a double; re-checking it everywhere is scattered validation; a passport checked once is a type that validates in its constructor; refusing a library card at the border is the compiler rejecting a WorkoutId where a UserId is expected; knowing its expiry is behavior on the value. The analogy mapped onto code. A sticky note is a raw primitive such as a double; re-checking it everywhere is scattered validation; a passport checked once is a type that validates in its constructor; refusing a library card at the border is the compiler rejecting a WorkoutId where a UserId is expected; knowing its expiry is behavior on the value.
The note and the passport, mapped onto the code.

The workout class

Here’s a workout in a running app: a user, a sport, a distance and a duration, and a method that works out the pace.

class Workout {
    String userId;
    String sport;      // "run", "ride" or "swim"
    double distance;   // km
    int duration;      // seconds

    double minutesPerKm() {
        return duration / 60.0 / distance;
    }
}

It’s quick to write, and it’s honest about its units: the comments say kilometers and seconds. For a prototype, this is reasonable.

Why it hurts

Then Maria’s watch starts syncing. She runs ten miles in eighty minutes, and the watch sends 10:

Workout w = new Workout();
w.userId = watch.owner();
w.sport = watch.activity();
w.distance = watch.distance();
w.duration = watch.seconds();

Units. The app reads 10 as kilometers. Her pace shows 8.00 minutes a kilometer; the real pace is 4.97. The comment said kilometers, and nothing checked the comment.

Identity. share(String workoutId, String userId) takes two strings. Swap them, and it compiles.

Rules everywhere and nowhere. The watch says "Run" with a capital R, so her run is missing from the weekly total. A bad sync sends a negative distance, and it’s accepted. Every service that reads a workout checks the values its own way, or not at all.

The same raw distance value is checked three different ways: the stats service requires distance greater than 0, the feed requires greater than or equal to 0, and the export checks nothing. The same raw distance value is checked three different ways: the stats service requires distance greater than 0, the feed requires greater than or equal to 0, and the export checks nothing.
One value, three different rules, one of them missing.

How to spot it

  1. The type lives in a comment or a name: kilometers in a comment, seconds in a variable name.
  2. The same check, repeated wherever the value is used.
  3. Several IDs of the same type, side by side.
  4. Strings or numbers used as kinds, like "run", "ride" and "swim". Fowler and Beck call this stringly typed code.
  5. Little helpers about one value, scattered around: formatPhone, isValidEmail, toMiles.

If a comment has to tell you the type, the code doesn’t.

The key insight: rules belong to the type

A primitive can hold the value, but not its rules: not the unit, not the valid range, not what it identifies. A small type can hold them. It checks the value once, when it’s made. After that, everyone trusts it, and the compiler refuses it in the wrong place.

If it has rules, give it a type.

The fix: Replace Primitive with Object

The refactoring is called Replace Primitive with Object (older names: Replace Data Value with Object, Replace Type Code with Class). Here’s distance, as a record:

record Distance(double meters) {
    Distance {
        if (meters < 0) {
            throw new IllegalArgumentException(
                "negative distance");
        }
    }

    static Distance ofKm(double km) {
        return new Distance(km * 1000);
    }

    static Distance ofMiles(double miles) {
        return new Distance(miles * 1609.344);
    }

    double km() {
        return meters / 1000;
    }
}

Inside, it keeps one unit: meters. The compact constructor refuses a negative distance, once, for every distance that will ever exist. Named factories bring values in, ofKm and ofMiles (an international mile is exactly 1,609.344 m), and one method takes them out, in kilometers.

For the duration, the JDK already has a type: java.time.Duration carries its own unit.

Now the sync code decides the unit once, at the edge, where the watch data comes in:

Workout w = new Workout(
        new UserId(watch.owner()),
        Sport.valueOf(watch.activity().toUpperCase()),
        Distance.ofMiles(watch.distance()),
        Duration.ofSeconds(watch.seconds()));

Ten miles becomes just over sixteen kilometers, and her pace comes out at 4.97 minutes a kilometer.

Primitives arrive from outside, in the watch data: a number in miles, a string, a number of seconds. At the edge they are converted once into Distance, Sport and Duration. Inside the app only the types are used. Primitives arrive from outside, in the watch data: a number in miles, a string, a number of seconds. At the edge they are converted once into Distance, Sport and Duration. Inside the app only the types are used.
Primitives outside, types inside: convert once, at the edge.

Check once, then trust the type.

IDs and kinds

IDs get the same treatment. A user ID and a workout ID become tiny records, one line each, and the sport becomes an enum:

record UserId(String value) { }
record WorkoutId(String value) { }

enum Sport { RUN, RIDE, SWIM }

interface Sharing {
    void share(WorkoutId workout, UserId with);
}

Now swap the arguments to share, sharing.share(maria, run), and it doesn’t compile: the compiler says incompatible types: UserId cannot be converted to WorkoutId. A typo like Sport.RNU won’t compile, and a bad value from the watch fails loudly at the edge: Sport.valueOf("HIKE") throws IllegalArgumentException. Fowler calls this move Replace Type Code with Class.

And the workout becomes a record of real types. Pace now reads like the sentence it is:

record Workout(UserId user, Sport sport,
               Distance distance, Duration time) {
    double minutesPerKm() {
        return time.toSeconds() / 60.0 / distance.km();
    }
}
Class diagram of the refactored Workout record: it holds a UserId, a Sport enum with RUN, RIDE and SWIM, a Distance with meters, ofKm, ofMiles and km, and a java.time Duration. Class diagram of the refactored Workout record: it holds a UserId, a Sport enum with RUN, RIDE and SWIM, a Distance with meters, ofKm, ofMiles and km, and a java.time Duration.
A record of real types.

If that Sport enum then drives the same switch in many places, that’s a different smell, and it’s the next one in this series: Switch Statements.

Three myths

  • “Just name it distanceKm.” A name helps the reader, not the compiler. double distanceKm = watch.distance(); still accepts miles.
  • “A type for every value is overkill.” A record is one line, and you only add one where a value has rules, a unit or an identity.
  • “So never use primitives.” No. The primitive doesn’t vanish. It moves inside one type (Distance holds a double), where its rules live with it.

Writing “official” on a sticky note doesn’t make it a passport. A name is a hope. A type is a check.

A second example: the JDK took the same medicine

Thread.sleep(5000). Five thousand what? Milliseconds, if you remember. Since Java 19, sleep also takes a Duration, and the call says its own unit:

Thread.sleep(5000);
Thread.sleep(Duration.ofSeconds(5));

It’s a move the platform made before. Dates and times moved from long millisecond counts to java.time in Java 8. File names moved from strings to java.nio.file.Path in Java 7. Each new type carries the unit or the rules that the old primitive left to the caller.

Timeline of the JDK replacing primitives with types: Java 7 added Path for file names, Java 8 added java.time for dates and times, Java 19 added Thread.sleep(Duration). Timeline of the JDK replacing primitives with types: Java 7 added Path for file names, Java 8 added java.time for dates and times, Java 19 added Thread.sleep(Duration).
The platform's own moves away from primitives.

Money is the classic case in business code: an amount without its currency is the same kind of guess. java.util.Currency and BigDecimal give you the parts; a small Money record holds them together.

Commonly confused: data clumps and switch statements

  • Data Clumps is several values that belong together, like a latitude and a longitude. Primitive Obsession is one value that deserves a type. The two often overlap: Fowler calls groups of primitives that travel together data clumps.
  • Switch Statements: here, a string kind became an enum. If the same switch on that enum turns up in many classes, polymorphism is the cure.
One value with rules but no type is Primitive Obsession, fixed by Replace Primitive with Object. Several values that travel together are Data Clumps, fixed by Extract Class or Introduce Parameter Object. A kind that is switched on in many places is Switch Statements, fixed by polymorphism. One value with rules but no type is Primitive Obsession, fixed by Replace Primitive with Object. Several values that travel together are Data Clumps, fixed by Extract Class or Introduce Parameter Object. A kind that is switched on in many places is Switch Statements, fixed by polymorphism.
One value, a group, a kind.

When it’s fine

  • Counters, indexes and loop variables. An int that counts laps has no rules beyond being a number: for (int i = 0; i < laps; i++).
  • At the edges. JSON fields and database columns are primitives. Convert them at the boundary, the way the sync code did.
  • Values with no rules at all. A free-text note on a workout is a string, and that’s all it needs to be.

Recap

Primitive obsession is keeping domain values in raw numbers and strings. Look for types hiding in comments, repeated checks, look-alike IDs and stringly typed kinds. Replace the primitive with a small type. Check it once, convert at the edge, and let the compiler refuse the wrong value.

Recap chain: spot the rule, make the type, check once, convert at the edge. Recap chain: spot the rule, make the type, check once, convert at the edge.
If it has rules, give it a type.

Checklist:

  • Does a comment or variable name carry a unit or a format?
  • Is the same validation written in more than one place?
  • Can two IDs of the same primitive type be swapped in a call?
  • Is a string or int used to mean a kind?
  • Would a one-line record with a compact constructor remove all of the above?

If it has rules, give it a type.

Related: Long Parameter List (same-typed parameter runs are the same risk) and Feature Envy (helpers like toMiles want to move onto the new type).

Further reading