Magic Numbers

Magic numbers term refers to using numbers directly in your code. The assumption among some developers is that each number should have a variable name assigned to it. However, the general rule is that only unclear or repeating numbers should be assigned to a constant for readability and maintainability. There is a difference.

A good example would be the greatest number in the whole world – 3.14159265358979323846. You don’t want to use this number each time you need it in your code. Assigning it to a constant would be a much better solution. Your developer buddies will love you to death for doing that.

Sometimes you want the real number in your code. A good example would be specifying constraint constant in code when setting up a static view. When you specify a top constraint constant, that space will most likely be very specific to that view and will never change. There is absolutely no reason or rhyme in creating a constant variable.

You generally want to avoid the obsession with replacing each number you use in your code with a constant. Especially if the number is self explanatory. Think about how many variables you will need to declare and the time it will take to look up values for each one of those if the need presents itself.

There is a theory and there is an actual practical implementation.

The question still remains unanswered though… “how do you know when to use constants vs numbers in your code?” Simplest answer would be, if the number you are using is repeating, or unclear, or being used multiple times, create a constant… If you need to specifically adjust something inside of a function, for example, and its perfectly clear why specific value was used, use a number.

It is also important to note that if the number can be inferred by a calculation, do that instead. A good example would be adding a button above the tab bar. Instead of using numeric value of 49 points (height of the tab bar), use

to find out the height of the bar and do the necessary Y offset of your button. The cool thing about this approach is that if the UITabBar become 40 points tall, your layout will still look great.

Magic Numbers