Robin Berjon

For Whom The Belle Trolls

Rant Of The Week

Numerical Constants Must Die

Robin Berjon - # -

Interfaces regularly require constant identifiers. You have a node and you want to know if it's an element or a comment. You have a message and you want to know if it's email or SMS. That makes sense. What baffles me is why in designing these APIs we insist on naming things with numbers when we could name them with, you know, names.

There are several options in this cargo cult. First, is the lovingly terse approach:

if (foo.type === 17) doSomething();

Then there is the comment you have to paste every time:

// check if this of the fungible type
if (foo.type === 17) doSomething();

Or we can have the uselessly long variant:

if (foo.type === FooInterface.FUNGIBLE_TYPE) doSomething();

And there's the meh option:

var isFungible = FooInterface.FUNGIBLE_TYPE;
// ...
if (foo.type === isFungible) doSomething();

Somehow it strikes me that nothing quite beats a simple application of:

if (foo.type === "fungible") doSomething();

It doesn't stop there. In specifications we keep writing interfaces that look useless complex because we list a dozen numerical constants that are values for just a simple field. And then, when one has to derive from that interface and needs to add new types (which has happened several times before) then it is anyone's guess where the new constants should start counting from in the face of multiple people doing the same thing or the interface evolving over time. Using strings, the acceptable set of which can simply be listed in prose, has none of these problems. And many other advantages. So why do we keep doing this to ourselves?

I for one have always hated the numerical constants in the DOM, if we could avoid propagating that I'm all for it. It's not like we're standardising UNIX system calls in the 1970s.

This article is part of a series on the Device APIs Working Group (DAP).