I think one thing to consider with magic numbers is, could they ever change. Consider a tax rate, for example. Sure, you could just make tax part of a formula to add a certain percentage of tax to a total, but thatâs a number that could potentially change every few years. On the other hand, it pretty safe to say that the number of days in a month wonât change in any of our lifetimes.
Another consideration is how often that number is used throughout an app. If the number is used in several places, then it probably makes sense to have it as a global variable. Then in the event that you ever need to change that number, you only need to change it in one place.
Itâs a matter of how easy you can make it to find and change a number in the event that you ever need to in the future. Whether itâs well labeled variables, or very thorough documentation.
Think of how glide uses CSS. They most likely have a master CSS stylesheet that controls the CSS for all apps. Whenever they want to make a change to how a component looks, they only have to change it in one place and every single one of our apps is automatically updated. On the other hand, when one of us chooses to add CSS which overrides the CSS from that master stylesheet, then it only affects one screen in one app. Magic numbers are really the same. They can either be a global defined variable, or they can be super specific to one little section of a function or formula.
In the code world, documentation is key. Whether itâs naming variables in a way that tells the developer their type and purposeâŚor simply adding comments to your code which describes what a function does and how it works. A lot of times you need to consider that someone else will have to look at that code and make sense of it years in the future.
At my day job, I work as a developer. There are some wicked math formulas that we deal with, that are provided by the government. Some of it uses lookup tables with millions of records to get specific variables for math formulas, some of it uses static numbers that never change, and some of it uses global variables that are used in multiple calculations. Itâs kind of all over the place, but in most cases everything is well documented so we can match up the code to the specs when needed. Through the years, a lot of our code has been updated to use table driven variables, so itâs a lot easier bto make the code run differently by changing some values in a table. The most frustrating part though, is when Iâm looking into a bug, but I run across code that was added 10 years ago with little to no documentation. I end up spending a lot of time trying to figure out what the code is supposed to be doing, so I can then figure out how to fix it. It can be very time consuming.
In the end, just make sure you can look at something several years from now and easily understand what itâs doing so you can maintain it if necessary.