# Primitive ObsessionA 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.

{{< lesson-video youtube="2Ka5VqQp26I" title="Primitive Obsession" >}}

## 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.

```mermaid {alt="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." caption="The numbers were right. The units were not."}
flowchart LR
  G["ground software<br/>writes lbf·s"] -->|"a bare number"| N["navigation<br/>reads N·s"]
  N --> R["trajectory off × 4.45"]
  class G,N warn
  class R bad
```

> **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).

```mermaid {alt="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." caption="The note and the passport, mapped onto the code."}
flowchart LR
  A["sticky note"] --> A2["double distance"]
  B["everyone re-checks it"] --> B2["validation in every service"]
  C["passport, checked once"] --> C2["record with a compact constructor"]
  D["library card refused"] --> D2["compiler refuses the wrong type"]
  E["knows its expiry"] --> E2["behavior lives on the value"]
  class A2,B2 bad
  class C2,D2,E2 good
```

## 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.

```java
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:

```java
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.

```mermaid {alt="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." caption="One value, three different rules, one of them missing."}
flowchart LR
  D["double distance"] --> S["stats: above zero"]
  D --> F["feed: zero or more"]
  D --> E["export: (no check)"]
  class D warn
  class S,F muted
  class E bad
```

## 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:

```java
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:

```java
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.

```mermaid {alt="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." caption="Primitives outside, types inside: convert once, at the edge."}
flowchart LR
  subgraph outside["outside: the watch"]
    direction TB
    O1["10.0 (miles)"]
    O2["Run (a string)"]
    O3["4800 (seconds)"]
  end
  subgraph inside["inside: the app"]
    direction TB
    I1["Distance"]
    I2["Sport.RUN"]
    I3["Duration"]
  end
  O1 -->|"Distance.ofMiles"| I1
  O2 -->|"Sport.valueOf"| I2
  O3 -->|"Duration.ofSeconds"| I3
  class O1,O2,O3 muted
  class I1,I2,I3 good
```

> **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:

```java
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:

```java
record Workout(UserId user, Sport sport,
               Distance distance, Duration time) {
    double minutesPerKm() {
        return time.toSeconds() / 60.0 / distance.km();
    }
}
```

```mermaid {alt="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." caption="A record of real types."}
classDiagram
  class Workout {
    UserId user
    Sport sport
    Distance distance
    Duration time
    minutesPerKm() double
  }
  class Distance {
    double meters
    ofKm(double) Distance
    ofMiles(double) Distance
    km() double
  }
  class Sport {
    <<enumeration>>
    RUN
    RIDE
    SWIM
  }
  class UserId {
    String value
  }
  Workout --> Distance
  Workout --> Sport
  Workout --> UserId
```

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](/code-smells/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:

```java
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.

```mermaid {alt="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)." caption="The platform's own moves away from primitives."}
flowchart LR
  A["Java 7<br/>Path for file names"] --> B["Java 8<br/>java.time for dates"] --> C["Java 19<br/>sleep(Duration)"]
  class A,B,C good
```

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](/code-smells/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](/code-smells/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.

```mermaid {alt="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." caption="One value, a group, a kind."}
flowchart TD
  Q{"what do you see?"}
  Q -->|"one value, rules, no type"| P["Primitive Obsession<br/>Replace Primitive with Object"]
  Q -->|"several values travel together"| D["Data Clumps<br/>Extract Class"]
  Q -->|"a kind switched on everywhere"| S["Switch Statements<br/>polymorphism"]
  class P c4
  class D c6
  class S c5
```

## 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.

```mermaid {alt="Recap chain: spot the rule, make the type, check once, convert at the edge." caption="If it has rules, give it a type."}
flowchart LR
  A["spot the rule"] --> B["make the type"] --> C["check once"] --> D["convert at the edge"]
  class D good
```

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](/code-smells/long-parameter-list/) (same-typed parameter runs are
the same risk) and [Feature Envy](/code-smells/feature-envy/) (helpers like `toMiles` want to
move onto the new type).

## Further reading

- Martin Fowler and Kent Beck, *Refactoring* (2nd ed., 2018), chapter 3, "Primitive Obsession".
- Refactoring catalog: [Replace Primitive with Object](https://refactoring.com/catalog/replacePrimitiveWithObject.html),
  [Replace Type Code with Subclasses](https://refactoring.com/catalog/replaceTypeCodeWithSubclasses.html).
- [Mars Climate Orbiter](https://en.wikipedia.org/wiki/Mars_Climate_Orbiter) and the NASA Mishap Investigation Board Phase I report (1999).
- [JEP 395: Records](https://openjdk.org/jeps/395); Javadoc for `java.time.Duration` and `Thread.sleep(Duration)`.
