What is a magic number?
Why do many programmers advise that they be avoided?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A magic number is a direct usage of a number in the code.
For example, if you have (in Java):
This should be refactored to:
It improves readability of the code and it’s easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.
The JDK is full of examples like in
Integer,CharacterandMathclasses.PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.