Constantly Magic Numbers

Posted on

Consider the following:


This is considered good practice, but I will often hear this from people:

Why should I put it in a constant? It’s not like the boiling point of water is going to change so why would we need that flexibility to be able to change it later?

They would be correct in assuming that it will never change, but the key here is the fact that you’ve named it. Using the constant instead of a magic number is about context. When someone else (or you down the road) reads the code again, numbers like 32 and 212 might not have the same semantic meaning or it might not be clear.

Using a constant allows you give it a name and specify exactly what that number means. The actual data is secondary information and is important only to the computer.

TL;DR: Always name your numbers!

© Sam Thompson