Today I was browsing through some questions on this site and I found a mention of an enum
being used in singleton pattern about purported thread safety benefits
In my opinion, all the answers you got up to now are valid, but in my experience, I would express it in a few words:
Use enums if you want the compiler to check the validity of the value of an identifier.
Otherwise, you can use strings as you always did (probably you defined some "conventions" for your application) and you will be very flexible... but you will not get 100% security against typos on your strings and you will realize them only in runtime.
Apart from all said by others.. In an older project that I used to work for, a lot of communication between entities(independent applications) was using integers which represented a small set. It was useful to declare the set as enum
with static methods to get enum
object from value
and viceversa. The code looked cleaner, switch case usability and easier writing to logs.
enum ProtocolType {
TCP_IP (1, "Transmission Control Protocol"),
IP (2, "Internet Protocol"),
UDP (3, "User Datagram Protocol");
public int code;
public String name;
private ProtocolType(int code, String name) {
this.code = code;
this.name = name;
}
public static ProtocolType fromInt(int code) {
switch(code) {
case 1:
return TCP_IP;
case 2:
return IP;
case 3:
return UDP;
}
// we had some exception handling for this
// as the contract for these was between 2 independent applications
// liable to change between versions (mostly adding new stuff)
// but keeping it simple here.
return null;
}
}
Create enum
object from received values (e.g. 1,2) using ProtocolType.fromInt(2)
Write to logs using myEnumObj.name
Hope this helps.
Besides the already mentioned use-cases, I often find enums useful for implementing the strategy pattern, following some basic OOP guidelines:
The simplest example would be a set of Comparator
implementations:
enum StringComparator implements Comparator<String> {
NATURAL {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
},
REVERSE {
@Override
public int compare(String s1, String s2) {
return NATURAL.compare(s2, s1);
}
},
LENGTH {
@Override
public int compare(String s1, String s2) {
return new Integer(s1.length()).compareTo(s2.length());
}
};
}
This "pattern" can be used in far more complex scenarios, making extensive use of all the goodies that come with the enum: iterating over the instances, relying on their implicit order, retrieving an instance by its name, static methods providing the right instance for specific contexts etc. And still you have this all hidden behind the interface so your code will work with custom implementations without modification in case you want something that's not available among the "default options".
I've seen this successfully applied for modeling the concept of time granularity (daily, weekly, etc.) where all the logic was encapsulated in an enum (choosing the right granularity for a given time range, specific behavior bound to each granularity as constant methods etc.). And still, the Granularity
as seen by the service layer was simply an interface.
Now why and what for should I used enum in day to day programming?
You can use an Enum to represent a smallish fixed set of constants or an internal class mode while increasing readability. Also, Enums can enforce a certain rigidity when used in method parameters. They offer the interesting possibility of passing information to a constructor like in the Planets example on Oracle's site and, as you've discovered, also allow a simple way to create a singleton pattern.
ex: Locale.setDefault(Locale.US)
reads better than Locale.setDefault(1)
and enforces the use of the fixed set of values shown in an IDE when you add the .
separator instead of all integers.
Use enums for TYPE SAFETY, this is a language feature so you will usually get:
Enums can have methods, constructors, you can even use enums inside enums and combine enums with interfaces.
Think of enums as types to replace a well defined set of int constants (which Java 'inherited' from C/C++) and in some cases to replace bit flags.
The book Effective Java 2nd Edition has a whole chapter about them and goes into more details. Also see this Stack Overflow post.
enum
means enumeration i.e. mention (a number of things) one by one.
An enum is a data type that contains fixed set of constants.
OR
An
enum
is just like aclass
, with a fixed set of instances known at compile time.
For example:
public class EnumExample {
interface SeasonInt {
String seasonDuration();
}
private enum Season implements SeasonInt {
// except the enum constants remaining code looks same as class
// enum constants are implicitly public static final we have used all caps to specify them like Constants in Java
WINTER(88, "DEC - FEB"), SPRING(92, "MAR - JUN"), SUMMER(91, "JUN - AUG"), FALL(90, "SEP - NOV");
private int days;
private String months;
Season(int days, String months) { // note: constructor is by default private
this.days = days;
this.months = months;
}
@Override
public String seasonDuration() {
return this+" -> "+this.days + "days, " + this.months+" months";
}
}
public static void main(String[] args) {
System.out.println(Season.SPRING.seasonDuration());
for (Season season : Season.values()){
System.out.println(season.seasonDuration());
}
}
}
Advantages of enum:
for more