Use a Java Enum with Strings
1 min read

Use a Java Enum with Strings

Use a Java Enum with Strings

In my project I wanted to log messages using predefined categories. Traditionally, I do it via classes (if the messages are specific to the functions provided by that class):

public class LogWrapper {
    public static final String EVENT_ERROR = "Error";
    public static final String EVENT_LOAD = "Load";

    // ...
};

or an interface (pretty much the same thing):

public interface LogEvents {
    String EVENT_ERROR = "Error";
    String EVENT_LOAD = "Load";
};

These solutions are prone to errors (e.g. when performing copy-paste and forgetting to change the string), so I wondered if there is an enum-based approach.

Of course there is:

public enum LogEvents{
    EVENT_ERROR("Error"),
    EVENT_LOAD("Load"),
    EVENT_OK("OK");


    private String value;

    LogEvents(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }
}

Quite nice, but more verbose than the interface variant (and also prone to the copy-paste duplication). That's why I ended up sticking with the interface approach for the time being.