Writing Clean Code and Magic Numbers

Magic Numbers

In programming hard-coding refers to puttng something in code that cannot be changed externally. A magic number is a hard-coded number in code. You should not use magic numbers in your code since it increases noise in the code. Let me explain what exactly it means.

Magic Number

Which of the following would you rather read?

  • Aditi went to the #101 dealer to buy #20 #555
  • Aditi went to the Ferrari dealer to buy a Red Ferrai-Enzo
The Human brain works better to understand in the second way. The latter is more memorable and readable than the former statement. This applies to programming as well.

Let's say you are writing a function to set the age of the user as given below. The age > 21 is not so readable to another programmer because 21 can be a legal driving license age or legal age for marriage or can be anything depending on the business needs. It's a magic number or it's been hard-coded into your code. So this should be removed.

program

You can make it a little more readable by declaring a constant legalDrinkingAge. If you want to still remove 21 from your class then you can add it to configuration files or property files and then read it at runtime. But the entire concept is to keep it more readable.



Another good way to remove magic numbers is by using enumerations (enum) . You have written a function to set the Status of a user, where you are using the condition status == 0 . What is no# 0 , it can be active status or inactive or locked or anything. So how to write better code? An enum comes to your help.



Let's first declare an enum StatusType and then modify the dirty code to make it more readable and clean.

declare enum StatusType

 


Similar Articles