Enums can also hold data and associate different behaviour to each Enum constant. This can reduce code and maintenance dramatically. Use of Enum constants can also help mitigate some security issues.

The simple enum

publicenum SimpleEnum {ONE,TWO;}

This provides two immutable constants. Once upon a time these would have been PUBLIC STATIC FINAL objects e.g

public static final Integer ONE = “One”;

This let an IDE such as Eclipse warn of typing mistakes and human memory bugs but resulted in classes with vast numbers of strings that had, for safety, to be unique throughout the application. The situation was even worse with Integers as some developers would remember the value of the constant and use the valuenot the constant. This resulted in bugs other developers loved to spend hours tracking down: after which they might track down the perpetrator and inform them forcefully of the error of their ways.

Enums allow packaging constants needed by a class or system in one place in compact easily maintainable fashion.
No more worrying about capitalisation (I recall a typo in a manual that cost three people a week of debugging till someone suggested changing the initial latter of a string from lowercase to uppercase, in contradiction of the manual).

Enums with data

Enum constants can also hold data for example

publicenum ComplexEnum {

UK("hello", "world"), US("hi", "man");

privatefinal String first,second;

//Mandatory constructor. The order of arguments

//in the constructor matches the order in the constant.

private ComplexEnum(String w1, String w2) {

first = w1;

second = w2;

}

public String eval(){ return first + " " + second;}

public String getFirst(){ return first; }

public String getSecond(){return second;}

}

The Strings need not be final, but if they are not final accessor methods should be defined.

public getStringfromType(ComplexEnum type){

if(type==UK)return “hello”

if()

…..

}

Similarly creating an eval() method for each constant can radically simplify the design of an application.

Since an Enum constant is immutable it can safely be included in SQL calls without creating an SQL injection vulnerability.

The Wrap

Enums provide typesafe constants and allow data and methods to be associated with each constant.

One can think of an Enum as a way to encapsulate a base class and a set of sub classes (Enum constants) each with different implementations of a method and different field values, accessed through protected accessors.

Used intelligently enums can reduce the size and maintenance load of code, avoid some types of security vulnerability and dramatically reduce the size and complexity of an implementation.

I help run our Bed and Breakfast (http://www.badjao.co.uk) and have a blog on Edinburgh: http://therealbadjao.blogspot.co.uk/ plus writing on Hubpages (http://hubpages.com/@alexk2009) on a variety of topics.