Magic Numbers Are Bad
I had my friend Clint Rutkas review some code of mine. Now I have been writing code longer than Clint has been alive but he’s a very smart guy and he writes more production code than I do these days. He;s written a lot of the Channel 9 projects. He’s famous for his Kinect driven lounge chair for example. Since his code is a lot more public than what I write most of the time he’s pretty careful about best practices so I knew he would be a good reviewer. As it turns out he was able to point out some rookie errors I made. Particularly that I was using “magic numbers.” And I was using them a lot. What is a magic number? It can mean several things and Wikipedia has a whole post on magic numbers. But in this case the following definition explains what I was doing:
Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants
Why is this bad? The two reasons in this code are one that it introduces multiple points of error and it makes the code hard to understand/support. Since I was using this number in a bunch of places I would have to be very careful not to miss one if I changed things. By using a named constant I could easily make the change in one place and “fix” all occurrences. The second problem is that it is not at all clear what the numbers mean, how they are selected and what happens if you change them. This makes support a real problem. So I need to go back and fix that.
In fact I need to look at which of those numbers are really constants and which should be calculated based on something. In at least one case the number that is hardwired in is the width of an object. What happens if I change that object? Actually I did and that caused me to change the magic number. This should have been a slap on the head to fix the underlying issue but it wasn’t. Clearly I need to make haste more slowly. Well we live and we learn. The good news is that this will all show up in a future post so hopefully others can learn from my errors.
Comments
- Anonymous
February 14, 2012
Wasn't aware of this term. Always referred to it as Hard Coded values. In our project we have a Constants.cs file where we have to put all these magic numbers. We use Dev Partner for coding standards verification and every .cs file is checked for hardcoded values except this specific file. All occurances are considered as error's. We deal with it in this way. Felt like sharing my views. Thanks Alfred, Very good post.