Editorials

No More Magic

I can still remember a code review with Adam, many years ago. He said, “You have magic numbers! That’s really bad.” Sadly, I didn’t even know what he meant, even though I had been coding for years.

Adam went on to explain that Magic Numbers are those times when you create a variable and set it to a scalar value. Sometimes the meaning of that value can be understood (ish). Often, you have to go to your magic decoder ring to know what they mean. You can extend the concept to Magic Values/ The magic is not just restricted to numbers.

See if you can figure out what these magic values mean?

var isHappy = "Y";
var isUgly = "M";
var status = 23;
var color = 10;

You could probably guess correctly that isHappy = “Y” means that whatever is happy is true. The rest of the examples probably don’t mean anything. You have to find that box top or decoder ring with the key to interpret the values.

If you are developing code, this practice of Magic Values has an intrinsic, long term cost. Even if you can remember what all the different codes are, they don’t mean anything to a person not familiar with your system. Use a class, struct, enum, constant variable or some other construct to provide some meaning to the value. Sure, you could put a comment after the value. That means you have to put that comment everywhere you want to use that value.

Even in SQL Server I have done away with magic numbers. I’ll create a variable in the stored procedure to represent a constant to be used anywhere within the stored procedure. Doing so assures communication of intent everywhere the value is used.

DECLARE @StatusActive INT = 1
DECLARE @StatusInactive INT = 2
DECLARE @StatusDeleted INT = 3

Now I can use these variables anywhere after they are declared, and my intentions are clear.

Let’s make a pledge to make the magic go away. Here’s a shout out to Adam for helping me become a better developer.

Cheers,

Ben