r/codereview • • Nov 03 '26

Units of measure in code: four layers of defense, from cheapest to strongest

A bug class that’s easy to write and hard to see in review: a number with no unit. timeout = 30 is 30 seconds in one function and 30 milliseconds in another, and nothing complains.

The famous documented example is the Mars Climate Orbiter, lost in 1999. As I understand the investigation, one piece of software produced thruster impulse data in pound-force seconds while another expected newton-seconds. I’d treat the details with some caution, but the lesson is widely cited: the numbers were fine, and the unit was missing.

Here are four layers of defense. Each is more work than the one before and catches more.

Layer 1: put the unit in the name

timeout_seconds = 30
distance_meters = 120.5

Costs nothing, and makes a mismatch visible at the call site. Also name function parameters this way: def wait(timeout_ms: int).

Layer 2: make the type carry the unit

from datetime import timedelta

def fetch(url, timeout: timedelta): ...

fetch(url, timeout=timedelta(seconds=30))

Standard library types already do this for time. For other quantities, a small wrapper or a units library (in Python, a package like pint) turns a unit mismatch into an error instead of a silent wrong number. The cost is extra code and some learning curve.

Layer 3: convert at the boundary
Inside your program, pick one unit per kind of quantity (for example, everything in SI units, all times in UTC seconds), and convert at the places where data enters or leaves: files, APIs, user input, other systems. Document what each external field means.

Layer 4: test with values you know from outside
A test that uses a known conversion from a reference (for example, 1 inch is exactly 25.4 mm) can catch a wrong factor. A test that computes the expected value with the same formula as the code only repeats the mistake.

Where this is overkill: small scripts, and code where only one unit ever appears. I’d start with Layer 1 everywhere and add the others where mistakes are expensive: money, physical measurements, medical doses, billing by usage.

Other places units hide: currency (cents vs dollars, and which currency), percentages (0.05 vs 5), angles (degrees vs radians), and timestamps (seconds vs milliseconds since the epoch).

What’s the most common unit mix-up you see, and which layer do you actually use?

0 Upvotes

2 comments sorted by