Why you should avoid magic numbers

Sometimes when you are learning to code, people tell you to avoid magic numbers, that is, numbers that you write in the middle of your source files without any clear explanation, or even with explanation in comments.

But I tell you, even with explanation in comments, you should avoid it, and use constants, even in language that don’t have constants. For example most of my current coding is done using Lua, that has no concept of constants, yet sometimes in my files there are a couple of constants neatly grouped somewhere, with some special naming convention (FOR_EXAMPLE_ALL_CAPS_WITH_UNDERLINE).

Even farther than having constants, you can make functions that return values that you want. But why someone should have all this hassle? It has to do with maintenance of the code.

A priority when writing code, beside making it work (always remember this, user experience is ALWAYS first, even when you are doing something very very very backend, if your code somehow results in bad user experience, you are doing it wrong) is ease of maintenance, inexperienced programmers are usually tempted to make crazy tricks to show off, or attempt to make your code super blazing hyper amazingly fast, or create some really awesome architecture with thousands of layers of abstraction and so on.

Then someone comes here and say: “I don’t need maintenance! I am coding alone and I will remember where all my variables are and their meaning!” Then I ask, what if, you have to chance something that you hardcoded everywhere?

I made that mistake once, in my early programming days, I made a game that had a score input screen designed for devices with no keyboards (the game was for computers, but I designed it imagining a target device that would be a very simple phone, this was back before the invention of touch phones, my phone then was still black and white), so I made a grid of letters, and you could choose what letter to input by going to that letter with the arrow keys, navigating the grid until the chosen letter. In my naive ways, I hardcoded the position of everything, lots and lots and lots of numbers describing the layout of the screen and to what places the current position marker should go. And then… I had to change the game resolution.

That day, when I had to change resolution, opened my source and saw hundreds of magic numbers, that I learned how painful using magic numbers in first place can be. If I had used math and made a layout that could react to resolution on its own, it would be no need, but no, I made that program that needed magic numbers, I had two choices: Replace them all, or… delete the stupidity I’ve made, and do it again. I will let you figure on your own what was my choice, but this I can tell you, don’t use magic numbers, even if you are coding alone in your own project, because if you have to change them all, or if you forget anything about them, it WILL bite you back.