Replace magic number with named constants

Dattatray Kale
Technogise
Published in
2 min readAug 14, 2019

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, 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.

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.

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

Better way

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

Hence, replace magic numbers with named constants.

Originally published at https://beingcraftsman.com on September 8, 2018.

--

--

Dattatray Kale
Technogise

Software Craftsman & Cloud Engineer with 13+ years' expertise. Proficient in React, Angular, .NET, Node.js, Java, AWS, Azure. Proven leader in team building.