In my humble opinion, the main thing enums are good for is type safety.
Suppose you have a function which can be called with some option that has a fixed set of possibilities. Say, "sale" or "return". A really bad solution would be to pass in a string, like:
public void doTransaction(String type)
{
if (type.equals("sale"))
... do whatever ...
}
One big catch to this method is if someone were to try calling it with "Sale" or "sail". Unless the program verifies that only valid parameters are passed in, misspellings could give mysterious bugs.
So okay, many programmers created constants for this:
public final static int SALE=1, RETURN=2;
public void doTransaction(int type)
{
if (type==SALE)
... do whatever ...
}
That's much better, but it still has problems. Suppose we have two parameters:
public final static int SALE=1, RETURN=2;
public final static int DOMESTIC=1, FOREIGN=2;
public void doTransaction(int type, int locale)
{
if (type==SALE && locale==DOMESTIC)
... etc ...
}
Now someone gets confused and calls doTransaction(FOREIGN, SALE)
. This will compile successfully, pass any validity tests within the program, and give totally incorrect results. Because if you didn't catch it, the parameters are in the wrong order.
Enums solve this problem. If instead you write
enum SaleType {SALE, RETURN};
enum Locale {DOMESTIC, FOREIGN};
public void doTransaction(SaleType type, Locale locale)
... etc ...
Now if someone tries to write, doTransaction(Locale.FOREIGN, SaleType.SALE)
, they get a compile-time error, and immediately know that they have the parameters wrong.