Replace magic number with named constants

120308

What do you understand after reading the above number?

It is just raw data. The interpretation is left to the reader of the data.

However, the reader may not get the intent behind it.

  • It could be a zip code of a city.
  • It could be a birthday in DDMMYY  format.
  • It could be a telephone number without the area code.
  • It could represent N number of things.

Do you agree with me that using just raw data does not convey its intent?

Similarly, a magic number in code is like raw data which does not convey its intent to the reader of the code.

A magic number is a numeric value that is used in the code. This value has unexplained meaning and hampers readability of the code.

Above code reads like John failed to upload his profile picture because the size of the profile picture was more than 10000000.

Here I did not understand the meaning of magic number 10000000.

Whether it is a size in Bits, Byte, KB, MB, GB?

Well, let’s introduce the named constant and see what happens.

Now, the code reads more like John failed to upload his profile picture because the size of the profile picture was more than maximum allowed file size i.e. 10000000 bytes.

As soon as you give metadata about the data i.e. relevant data it becomes information to the reader. The reader can work with it easily as the intent is clear.

Another example:

Bad way

When the given day is 0 or 6, Magic number! then put ‘-’ in cell content.

Better way

When the given day is Sunday or Saturday then put ‘-’ in cell content.

Thus, named constants could be used to provide data about raw data so that reader of your code could easily figure out the intent.

Hence, Replace magic number with named constants.

Dattatraya Kale

Aspiring agile software craftsman, clean code, polyglot, in love with different programming paradigm. I am on a never-ending journey towards mastery of software.