Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)
Can anyone help me with the magic number? And why it is avoided?

1 Answer

0 votes
by (26.7k points)

Basically, magic number can be used directly in the code:

public class Foo {

    public void setPassword(String password) {

         // don't do this

         if (password.length() > 7) {

              throw new InvalidArgumentException("password");

         }

    }

}

It will also help you to improve the readability of the code and also it is very easy to maintain. One disadvantage is that, if you use the magic number and the max size changes then, you need to change it to both the code locations.

I hope this will help.

Want to know more about Java? Prefer this tutorial on Learn Java.

Want to become a Java Expert? Join Java Training now!!

Related questions

0 votes
1 answer
asked Feb 24, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...