Magic Numbers

“It’s harder to read code than to write it.” – Joel Spolsky in Joel on Software

When you write code with numbers that are constants and will not be changed and another person has to read it, they may not be able to comprehend it. So, they become ‘magic numbers’! Take a look at your own code written 10 months ago and you will know what I’m talking about. You may have already forgotten which number corresponds to the action you are referring to, in one of your branching statements. Therefore, it helps if you define this in the beginning of your program as a constant with a clear name.

For example:

if (presentYear == 2014)

This can be corrected to,

const year2014 = 2014
if (presentYear == year2014)

Congratulations, you will then be doing your bit to make your code more readable!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s