Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for global constants involving magic numbers

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?

like image 420
Billworth Vandory Avatar asked Oct 14 '10 08:10

Billworth Vandory


People also ask

What Is A magic number Why are magic numbers problematic?

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.

Is a magic number Magicnumber?

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.


1 Answers

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 :)

like image 183
willcodejavaforfood Avatar answered Sep 18 '22 15:09

willcodejavaforfood