Naming: No Magic Numbers
A common problem I see is the use of magic variables. Many developers already know what these are, but all do not. The concept is pretty simple and just about everyone agrees on it(I think). I’ve never heard any dissent.
The idea is that you shouldn’t inline strings or numbers. Now with strings, it may depend on the string, but we aren’t going to worry about that here. Let’s take a look at a good example I have found in the wild(in the Vue 3 source code), and what it would look like without.
See the example inline below. The point isn’t the enum declaration. The point is to make the isComment function declaration more readable. When reading the main logic of
isComment you can read
node.nodeType === DOMNodeTypes.COMMENT; as opposed to the alternative if the magic number had been inlined,
node.nodeType === 8
Let’s take a look at what the function would have looked like without. Now because of the short function it is still possible to infer what the 8 means, but it is certainly less obvious what’s going on.
That’s your alternative, and it’s a pretty bad alternative. The rule doesn’t apply only to numbers. It can apply to any value literal. Don’t inline numbers, strings, dates, object literals, without saving them to a variable first. This gives you the developer a chance to put some meaningful name to that literal, so future developers have a chance at knowing what