DEV Community

Serguey Asael Shinder
Serguey Asael Shinder

Posted on

Put the Unit in the Name

The field is called timeout.

Its value is 30.

Thirty what.

You know the answer
because you wrote the line.

The next person reads 30,
picks whichever reading
makes the code look sane,
and is right about half the time.

We had two services
that agreed perfectly on a number
and disagreed about what it meant.

One wrote a retry delay in seconds.

One read it as milliseconds.

Nothing failed.

The retries simply came back
fast enough to be indistinguishable
from an attack we were running
against ourselves.

Money is the same trick
with worse consequences.

A field called amount holds 1250.

Pounds, or pence.

One of those is a refund
and the other is a phone call
from somebody who received twelve pounds fifty
instead of twelve hundred and fifty.

Then there is the percentage
that is 0.2 in one table
and 20 in the next,
written by two teams
who each thought theirs was the obvious one.

The fix is not a comment.

A comment is a promise
that stops being kept
the first time somebody is in a hurry.

Put the unit in the name.

timeoutMs.
amountInPence.
discountFraction.
sizeBytes.

It is ugly.

It is ugly the way a label on a jar is ugly.

Where the language allows it,
put the unit in the type
and let the compiler do the arguing.

A duration cannot be added
to a number of bytes,
and no reviewer should have to notice that.

Pay attention at the boundaries,
because that is where every one of these lives.

The JSON body.
The column name.
The query string.
The environment variable.
The message on the queue.

Inside one function everybody knows.

Across a boundary nobody does.

So ask one question in review,
every time a number crosses anything.

Thirty what.

If the answer lives anywhere
except the name or the type,
it will be lost,
and it will be lost precisely
where it was the only thing that mattered.

A bare number is half the information,

travelling as though it were all of it.

– Serguey Asael Shinder

Top comments (0)