11

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?

midhunhk
  • 5,560
  • 7
  • 52
  • 83
Billworth Vandory
  • 5,003
  • 5
  • 29
  • 34

5 Answers5

30

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

willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
4

Yes it is. Enum is the best choice.

You are getting for free:

  • constants
  • immutable objects
  • singletons

All in one.

But wait, there's some more. Every enum value can have its own fields and methods. It's a rich constant object with behavior that allows transformation into different forms. Not only toString, but toInt, toWhateverDestination you need.

Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
  • 3
    And here's a guide on how to use Enums as constants http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html – Joel Oct 14 '10 at 08:29
2

Enum is best for most of the case, but not everything. Some might be better put like before, that is in a special class with public static constants.

Example where enum is not the best solution is for mathematical constants, like PI. Creating an enum for that will make the code worse.

enum MathConstants {
    PI(3.14);

    double a;        

    MathConstants(double a) {
       this.a = a;
    }

    double getValueA() {
       return a;
    }
}

Usage:

MathConstants.PI.getValueA();

Ugly isn't it? Compare to:

MathConstants.PI;
nanda
  • 24,458
  • 13
  • 71
  • 90
0

Forget about enums - now, when static import is available in Java, put all your constants in REAL class (instead of interface) and then just import the static members from all the other ones using import static <Package or Class>.

  • Can you clarify why we should, "forget about enums" and elaborate why you would want to import the constants from other classes statically? – allingeek Sep 26 '12 at 02:31
  • 1. The question was about magic numbers. Enumerations aren't good for numbers comparing to standard constants - see @nanda 's answer above. 2. Furthermore, enumerations are ugly decision when you have to store a set of different-type constants. 3. Enums were initially introduced as a container for _series_ of elements. Which means enumeration describes one logical set of units: months, days of week, planets, rainbow colors, etc; and it was a workaround to use enums for constants to avoid the 'interface constants' anti-pattern. Now it is not required anymore - we have static imports instead. – Mikhail Berastau Sep 28 '12 at 11:57
0

Using interfaces for storing constants is some kind of abusing interfaces.

But using Enums is not the best way for each situation. Often a plain int or whatever else constant is sufficient. Defining own class instances ("type-safe enums") are even more flexible, for example:

public abstract class MyConst {
  public static final MyConst FOO = new MyConst("foo") {
    public void doSomething() {
      ...
    }
  };

  public static final MyConst BAR = new MyConst("bar") {
    public void doSomething() {
      ...
    }
  };

  protected abstract void doSomething();

  private final String id;

  private MyConst(String id) {
    this.id = id;
  }

  public String toString() {
    return id;
  }
  ...
}
Mot
  • 28,248
  • 23
  • 84
  • 121
  • how is it more flexible than enums? they can have constant-specific methods too (abstract methods that each individual constant implements). – Norill Tempest Nov 05 '14 at 23:52