Programming and Magic Numbers

Recently, I have had to review a junior developer’s code and came across many unnamed numbers used in various code blocks repeatedly.This moved me to write this post as I am an avid advocate for Clean Code and Best Practices.
What is a Magic Numbers
Magic Number refers to the anti-pattern of using numbers directly in source code.Usually, they have unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants.This term though is not related to only numerical types: It applies to all types. Magic Number also has other meanings.See here
Examples
Now lets have a look at some examples of magic number representation in our day to day codes:
public class PhonenNumberValidator public boolean isPhoneValid(String phoneNumber){
if(phoneNumber.length() < 12){
return false;
}
return true;
}
.....
.....In this example for instance, 12 is a magic number.The best way to rewrite this is shown below:
public class PhonenNumberValidator private static final int MIN_PHONE_LENGTH = 12; public boolean isPhoneValid(String phoneNumber){
if(phoneNumber.length() < MIN_PHONE_LENGTH){
return false;
}
return true;
} .....
.....This is more clean and readable,the tendency of having duplicates is also reduced as MIN_PHONE_LENGTH can now be reused anywhere in the class instead of duplicating 12.
Advantages of Avoiding Magic Numbers
- Code Readability: It improves readability of the code. Magic numbers become particularly confusing when the same number is used for different purposes in one section of code.In this instance for example a programmer could be wondering what exactly 12 means.Eliminating the magic number makes is readable and easier to understand.
- Code is Maintainable: The above improved code can be easily maintain or refactored.Why ?,because It is easier to alter the value of the number from one point, as it is not duplicated.I will literally have to just reassign the value to a different number as opposed to changing it in multiple locations.
- It helps detect typos: Using a variable (instead of a literal) takes advantage of a compiler’s checking. Accidentally typing 22 instead of 12 would go undetected.
These are few of it benefits gathered,visit here for more information on magic numbers and even theirs trade-offs.
Hope this helps someone out there :-).If you liked this, kindly hit the clap icon up there. Thank you
