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.
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.
A number without a unit is a guess.
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).
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.
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.
"run", "ride" and "swim". Fowler and Beck call
this stringly typed code.formatPhone, isValidEmail, toMiles.If a comment has to tell you the type, the code doesn’t.
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 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.
Check once, then trust the type.
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();
}
}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.
distanceKm.” A name helps the reader, not the compiler.
double distanceKm = watch.distance(); still accepts miles.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.
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.
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.
int that counts laps has no rules beyond being a
number: for (int i = 0; i < laps; i++).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.
Checklist:
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).
java.time.Duration and Thread.sleep(Duration).