w3ctag / design-principles

A small-but-growing set of design principles collected by the TAG while reviewing specifications
https://w3ctag.github.io/design-principles
176 stars 46 forks source link

Should conceptually ordered enums still be strings? #443

Open LeaVerou opened 1 year ago

LeaVerou commented 1 year ago

We currently have the blanket guidance that all enums should be strings, not numbers.

Indeed, JS engines have no performance benefit from using numbers instead of strings. However, when the enum is ordered, numbers offer an additional benefit: comparison. Case in point: HTMLMediaElement.readyState. A developer can do:

if (myAudio.readyState < HTMLMediaElement.HAVE_FUTURE_DATA) {
    // ...
}

With strings, this would look like:

if (myAudio.readyState === "nothing" || myAudio.readyState === "metadata" || myAudio.readyState === "current") {
 // ...
}

which is far more awkward.

Therefore, I'm not sure it's the latter we should be recommending. Using ints here seems like a reasonable choice by the API designers.

However, if we change our guidance to be "you can use numbers when the enum is conceptually ordered", doesn't that make the Web Platform inconsistent, when some enums are strings and others are numbers (of course it already is inconsistent anyway, but the point of the design principles is to reduce inconsistency over time, not encourage it).

annevk commented 1 year ago

I don't think this example is compelling enough to change the advice. Also, while it might take a little longer to write, it's quite a bit clearer.

And if enough people end up writing something like that, that might perhaps be reason to add an instance method for it.