Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum property best practice

I've seen two approaches to handling enums with properties. Is one better than the other?

As a property:

public enum SEARCH_ENGINE {
    GOOGLE("http://www.google.com"),
    BING("http://www.bing.com");

    private final String url;

    private SEARCH_ENGINE(String url) {
        this.url = url;
    }

    public String getURL() {
        return url;
    }
}

As a method:

public enum SEARCH_ENGINE {
    GOOGLE {
        public String getURL() {return "http://www.google.com";}
    },
    BING {
        public String getURL() {return "http://www.bing.com";}
    };

    public abstract String getURL();
}
like image 863
JustinKSU Avatar asked May 12 '11 20:05

JustinKSU


People also ask

Should enum be uppercase or lowercase?

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 enums have properties?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

When should we use enum in Java?

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?

Enumerations make for clearer and more readable code, particularly when meaningful names are used. The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future.


1 Answers

The first clearly looks cleaner to me - it makes use of the commonality that each element of the enum will have a fixed String URL which is known at initialization. You're effectively repeating that "logic" in each implementation in the second version. You're overriding a method to provide the same logic ("just return a string which is known at compile-time") in each case. I prefer to reserve overriding for changes in behaviour.

I suggest making the url field private though, in the first.

like image 179
Jon Skeet Avatar answered Sep 20 '22 09:09

Jon Skeet