Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enumerations vs. static constants

Tags:

I'm looking at some Java code that are maintained by other parts of the company, incidentally some former C and C++ devs. One thing that is ubiquitous is the use of static integer constants, such as

class Engine {
    private static int ENGINE_IDLE = 0;
    private static int ENGINE_COLLECTING = 1;
    ...
}

Besides a lacking 'final' qualifier, I'm a bit bothered by this kind of code. What I would have liked to see, being trained primarily in Java from school, would be something more like

class Engine {
    private enum State { Idle, Collecting };
    ...
}

However, the arguments fail me. Why, if at all, is the latter better than the former?

like image 907
Christoffer Avatar asked Feb 09 '10 13:02

Christoffer


People also ask

Is it better to use enum or constant?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

Should I use enumerations?

The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future. Makes code easier to read, which means it is less likely that errors will creep into it.

What is the point of enumerations in Java?

In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types). Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

What is enumeration constant in Java?

A set of "enumerable constants" is an ordered collection of constants that can be counted, like numbers. That property lets you use them like numbers to index an array, or you can use them as the index variable in a for loop. In Java, such objects are most often known as "enumerated constants."


1 Answers

Why, if at all, is the latter better than the former?

It is much better because it gives you type safety and is self-documenting. With integer constants, you have to look at the API doc to find out what values are valid, and nothing prevents you from using invalid values (or, perhaps worse, integer constants that are completely unrelated). With Enums, the method signature tells you directly what values are valid (IDE autocompletion will work) and it's impossible to use an invalid value.

The "integer constant enums" pattern is unfortunately very common, even in the Java Standard API (and widely copied from there) because Java did not have Enums prior to Java 5.

like image 90
Michael Borgwardt Avatar answered Oct 26 '22 13:10

Michael Borgwardt