To avoid magic numbers, I always use constants in my code. Back in the old days we used to define constant sets in a methodless interface which has now become an antipattern.
I was wondering what are the best practices? I'm talking about global constants. Is an enum the best choice for storing constants in Java?
A magic number is a number in the code that seems arbitrary and has no context or meaning. This is considered an anti-pattern because it makes code difficult to understand and maintain. One of the most important aspects of code quality is how it conveys intention. Magic numbers hide intention so they should be avoided.
In programming, a magic number is a numeric value that is used directly in the code. It is used for identification purposes. In this section, we will discuss what is a magic number and how can we find a magic number through a Java program.
For magic numbers where the number actual has a meaning and is not just a label you obviously should not use enums. Then the old style is still the best.
public static final int PAGE_SIZE = 300;
When you are just labelling something you would use an enum.
enum Drink_Size
{
TALL,
GRANDE,
VENTI;
}
Sometimes it makes sense to put all your global constants in their own class, but I prefer to put them in the class that they are most closely tied to. That is not always easy to determine, but at the end of the day the most important thing is that your code works :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With