Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum overkill? [closed]

Tags:

java

enums

I have often the situation where I need a variable for a class that could be represented as simple enum type, for example:

private enum PageOrder {DOWN_THEN_OVER, OVER_THEN_DOWN};

If a declare the enum type within the class that holds the variable then I have to use the qualified name MyClass.PageOrder which is not comfortable. But if I create a new class I have a class for just a simple enum declaration, which seems overkill for me.

For that reason, I frequently use integers instead of enum type.

Any comments/suggestions on this topic?

like image 657
Neo Avatar asked Sep 24 '14 09:09

Neo


People also ask

Should enum values be capital?

Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.

Can we override enum in Java?

Enums are exactly final inner classes that extends java. lang. Enum<E> . You cannot extend, override or inherit an enum .

Are enums always static?

All Enums are implicitly static, its just you don't need to write the static keyword.


2 Answers

You can do

import static yourpkg.MyClass.PageOrder;

This will always work since inner enums are always static. Note that this works even in the file that defines the MyClass class.

like image 67
aioobe Avatar answered Oct 09 '22 16:10

aioobe


For that reason, I frequently use integers instead of enum type.

Please don't do that.

You can often choose a name for the parent class and the enum that actually helps the clarity of the code.

class Page {
    enum Order {
        DOWN_THEN_OVER, OVER_THEN_DOWN;
    }
}

// Accessing: A little verbose but clear and efficient.
Page.Order order = Page.Order.DOWN_THEN_OVER;

You can also static import each enum you use but I prefer the verbosity above.

import static com.oldcurmudgeon.test.Test.Order.DOWN_THEN_OVER;
import static com.oldcurmudgeon.test.Test.Order.OVER_THEN_DOWN;

public class Test {

    enum Order {

        DOWN_THEN_OVER, OVER_THEN_DOWN;
    }

    public void test() {
        Order pageOrder = DOWN_THEN_OVER;
    }

}

Obviously you cannot take this approach if the enum is private.

like image 39
OldCurmudgeon Avatar answered Oct 09 '22 16:10

OldCurmudgeon