7

I was recently discussing enums vs public static final constants with a friend. I told him that public static final constants are more maintainable than enums, sometimes faster (android developer docs confirm this), and more convenient as well. I also said that you lose functionality when using enums as well:

  1. You cannot extend an enum.
  2. You cannot instantiate an enum.

He then said you shouldn't be using an enum if you need to instantiate or extend an enum. I then replied that's why we should just use constants because it is more maintainable; What if mid project we need to instantiate an enum or extend it? Then we would have to change everything.

An example demonstrating enums vs constants I made to illustrate my point:

public enum WeekDay {
/*
 * We will start at 1 for demonstration
 */
SUNDAY("Sunday", 1), MONDAY("Monday", 2), TUESDAY("Tuesday", 3), WEDNESDAY(
        "Wednesday", 4), THURSDAY("Thursday", 5), FRIDAY("Friday", 6), SATURDAY(
        "Saturday", 7);
/*
 * Notice we cannot do this...This is where enums fail.
 */
// LUNES("lunes",1), MARTES("martes",2);

private String dayName;
private int dayIndex;

private WeekDay(String dayName, int dayIndex) {
    this.dayName = dayName;
    this.dayIndex = dayIndex;
}

public String getDayName() {
    return dayName;
}

public void setDayName(String dayName) {
    this.dayName = dayName;
}

public int getDayIndex() {
    return dayIndex;
}

public void setDayIndex(int dayIndex) {
    this.dayIndex = dayIndex;
}

@Override
public String toString() {
    return this.dayName + ":  " + this.dayIndex;
}

}

What if we need Spanish week days as well? The enum falls short because you cannot extend it (you would have to do some copy and paste action).

Contrast the enum with this:

public class WeekDayClass {

    private int dayIndex;
    private String dayName;

    public WeekDayClass(int dayIndex, String dayName) {
        super();
        this.dayIndex = dayIndex;
        this.dayName = dayName;
    }

    public int getDayIndex() {
        return dayIndex;
    }

    public void setDayIndex(int dayIndex) {
        this.dayIndex = dayIndex;
    }

    public String getDayName() {
        return dayName;
    }

    public void setDayName(String dayName) {
        this.dayName = dayName;
    }

    @Override
    public String toString() {
        return this.dayName + ":  " + this.dayIndex;
    }

    abstract static class Constants {

    }


    public static void main(String[] args) {
        WeekDayClass init = new WeekDayClass(10, "I can init new days here");

    }
}

And then I can extend it and make AmericanWeekDays:

public class AmericanWeekDay extends WeekDayClass {
    public AmericanWeekDay(int dayIndex, String dayName) {
        super(dayIndex, dayName);
    }

    static class AmericanConstants extends Constants {
        public static final WeekDayClass SUNDAY = new WeekDayClass(1, "Sunday");
        public static final WeekDayClass MONDAY = new WeekDayClass(2, "Monday");
        /*
         * And so on...
         */
    }

}

Or Spanish Week Days:

 public class SpanishWeekDays extends WeekDayClass {

    public SpanishWeekDays(int dayIndex, String dayName) {
        super(dayIndex, dayName);
    }

    static class SpanishConstants extends Constants {
        public static final SpanishWeekDays LUNES = new SpanishWeekDays(2, "lunes");
        /*
         * And so on...
         */
    }

}

Also to go even further:

public class WeekDayClass {

    private int dayIndex;
    private String dayName;

    public WeekDayClass(int dayIndex, String dayName) {
        super();
        this.dayIndex = dayIndex;
        this.dayName = dayName;
    }

    public int getDayIndex() {
        return dayIndex;
    }

    public void setDayIndex(int dayIndex) {
        this.dayIndex = dayIndex;
    }

    public String getDayName() {
        return dayName;
    }

    public void setDayName(String dayName) {
        this.dayName = dayName;
    }

    @Override
    public String toString() {
        return this.dayName + ":  " + this.dayIndex;
    }

    static class AmericanConstants {
        /*
         * Insert Constants Here
         */

    }

    static class SpanishConstants {
        /*
         * Insert Constants Here
         */
    }

}

I understand with an enum you could perhaps make a workaround using data structures (Lists) so you accommodate this shortcoming but why bother? With using public static constants I gain inheritance from the base class, cleaner code, possibly shorter code, and easier maintainability.

I also read that you can use enum's to better design "input parameters" but you could also do the same with the public static final constants as shown above.

Enums have the advantage of being able to be used in switch statements and have the inherited enum methods like values(). These methods can also be replicated if needed in "public static final constant" classes. Aside from the switch I don't see any enum advantages.

In conclusion, is an enum really better than public static final constants? If so, where did I go wrong? Is their something I am missing?

EDIT: You cannot use generics in enums as well.

4
  • How is a static final variable extendable? Dec 13, 2013 at 4:16
  • I meant the base class
    – horvste
    Dec 13, 2013 at 4:16
  • For anyone wondering, The android R system utilizes similar structures that I posted above.
    – horvste
    Sep 28, 2014 at 1:00
  • "Are enums less maintainable than public static final constants?" .... there are so many aspects that must be considered when arriving at an answer that is correct for your use case. Any attempt to provide a conclusive, universal yes-no answer to this question will fail. One particularly important aspect is serializability. Writing a robust, correct, instance controlled, and secure serialiable Java class is not a trivial matter. With a Java enum, you get this baked in for free.
    – scottb
    Jun 14, 2019 at 13:31

3 Answers 3

10

Enums get you a lot more than you seem to give them credit for, and while sometimes constants are required, this case is probably a win for enums.

First of all, there is no real difference between an "English weekday" and a "Spanish weekday", they represent the same values. Therefore, the best solution would be to do the conversion to string independently of what the values actually are through some kind of localization method. The values don't change with the language, their representation does.

This is entirely doable quickly and easily with enums. Just write it like this (a little pseudocode-y):

public enum Weekday {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    ...;

    public String toLocalizedString(Language l) {
        // interact with localization files
    }
}

You are conflating the ideas of external representation and internal representation. Your data should be as homogenous as possible because there is only ever going to be one Monday. It might be called different things, but it's still the same value.

Enums also get you a lot of niceness for free, though, which makes your code much clearer and more maintainable in the long run. Type checking, == comparison, and usability in switch are a few, with no boilerplate to speak of.

5
  • The "WeekDay" enum was just a (bad) example. For this example, using Language as a parameter is the "right way". As to the switch, couldn't we just make a Map<Language,Constants>?
    – horvste
    Dec 13, 2013 at 5:00
  • A better way to express this in this example is if the Spanish or American weekdays had an extra parameter in their constructor. For example, we could have a class "ChristianWeekDay" and have the superclass be "WeekDays" and then have an extra parameter in the constructor as "boolean isSabbath". Adjusting the enum in this case would be difficult.
    – horvste
    Dec 13, 2013 at 5:10
  • 1
    @horvste At that point you're divulging into extremely complicated localization differences. Localizing dates and times is historically one of the hardest things to get right. Don't roll your own. As for the general problem, it sounds to me like a problem that complex shouldn't use class constants or enums, you should use a real class hierarchy and implement a Calendar class, etc. I haven't ever seen a good situation in Java where class-constant enums are better than the builtin enum functionality. Dec 13, 2013 at 5:14
  • But using a class hierarchy after you based your constants off of an enum doesn't work out, unless you want to start over. It seems that using a hierarchy as shown in the question allows you greater flexibility at the cost of convenience. Why sacrifice flexibility for convenience?
    – horvste
    Dec 13, 2013 at 5:25
  • 1
    @horvste I fail to see how switching from an enum to a full class hierarchy is any harder than doing so from using class constants. Either way, you designed the system wrong and you need a major refactor. Both enums and class constants should be used for a limited set of constant values that won't change; you can't "extend" either one of them, and if you need that type of functionality, use classes. It's usually pretty clear when to use enums and when to use classes, but there are still no real advantages in flexibility if you choose class constants over enums. Dec 13, 2013 at 5:28
6

I think you're taking the usage of enums way to far and then come to a conclusion that they are not useful.

Enums are simply telling you that there's a limited and predefined number of options to choose from. Nothing more than that. For example, when you see a parameter that is an enum (let's say State) and it has 3 values (Pending, InProgress, Closed), you know that a state of some object can have one of those and only one of those values.

Enums provide an easy way of validating that a proper value is used as you cannot easily select a value that is not proper when coding. They are also a way of documenting as you can easily see what options are available.

2
  • Wouldn't it be better (more maintainable) to plan for the future? You limit your options with the enum. For example, I have the enum 'State'. Under the assumption, that the 'State' enum has methods that are specific to an objects "state" and are not just "markers" wouldn't it be better to leave the "polymorphic" properties intact so that we could reuse the code if we needed to, perhaps with a different object?
    – horvste
    Dec 13, 2013 at 4:32
  • 1
    If you need a more complex structure, you create a class, methods, etc. Enums are supposed to be a simple structure - you do not always need to overcomplicate. And limiting options is exactly what enums are for. And you can always add more values to them.
    – Szymon
    Dec 13, 2013 at 4:35
1

Enumerations wouldn't exist if they weren't useful - the same can be said of constants. Just like a screwdriver can remove a screw while a hammer can remove a nail - different tools in your programmer "toolbox" can be used for unique and important purposes. I suggest reading more about enumerations and constants and I think you will find why they exist and when to use them.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.