On Style: The Enum Pattern

I will often see JavaScript programmers writing code like:

[js]
document.onkeydown = function(evt) {
// …

if (key == 40) {
// …
}
};
[/js]

While this is certainly convenient for the person writing the code, it’s not so fun for anyone reading the code.

C# has the enum keyword which is really quite handy in situations like this. In its most basic form, you might have an enum for the names of the days of the week:

[csharp]enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};[/csharp]

The enum starts at zero so Days.Sat will equal 0, Days.Sun will equal 1, Days.Mon will equal 2, and so on.

So, in a calendar application, rather than comparing if today == 0, we’d write today == Days.Sat.

We can apply the same concept to JavaScript:

[js]
var KEYS = {
LEFT: 37
, UP: 38
, RIGHT: 39
, DOWN: 40
};
[/js]

Now we can rewrite our first example and make it much more readable:

[js]
document.onkeydown = function(evt) {
// …

if (key == KEYS.DOWN) {
// …
}
};
[/js]

This is further illustrated with the DOM nodeType values.

[js]
Node.ELEMENT_NODE == 1;
Node.ATTRIBUTE_NODE == 2;
Node.TEXT_NODE == 3;
[/js]

This enables us to write much more readable programs than:

[js]
if (document.getElementById("foo").nodeType === 1) {
//…
}
[/js]

Rather, we can write:

[js]
if (document.getElementById("foo").nodeType === Node.ELEMENT_NODE) {
//…
}
[/js]

This also increases maintainability. If we want to change `nodeType == 1`, how many occurences of “1” can we find with a find/replace? Moreover, how many of those occurences will be relevant?