Using Java Enums to replace conditional (IF) statements.

Hello,
Recently I was using Java Enumerations for addressing some requirements and while doing that I realized that one can write a much better and maintainable code using Enums.
I got rid of lot of conditional statements using Enum attributes in my code. It looks clean and easily understandable.
Here is how I utilized Java Enums. Hope you find this useful.

Scenario:
Consider that we have a list of Strings that represents days of the week.
Now if we want to print out the index of the day instead of its name then we might do something like below ,

Note that System.out.println() is just a an example function used to illustrate the example. We can use retrieved variable in whatever the business logic may be.


Solution I:

This is the naive way of handling this scenario.


if(day.equals("Monday")) {
 System.out.println("Index is " + 1);
} else if(day.equals("Tuesday")) {
 System.out.println("Index is " + 2);
} ...

...

and so on

Solution II:
Somebody might want to create a Map<String,Integer) that contains String “day” as key and “index” as value and easily get the index using the code snippet below


Map<String,Integer> daysofweek = new HashMap<String,Integer>();
daysofweek.put("Monday",1);
daysofweek.put("Tuesday",2);
..
..
int index = map.get("Monday");
System.out.println("Index is" + index);

The second solution seems to be more elegant than the Solution I, which relies on lot of if/else conditional statements to fulfill the requirement.
Instead of using a Map we can do the same thing using an Enumeration in Java 5.

Solution III:
We construct an Enum as below that has an attribute “index”.


public class EnumTest {

 enum daysofweek {
  MONDAY(1),
  TUESDAY(2),
  WEDNESDAY(3); //Not all the days are shown here

  private int index;

  daysofweek(int index) {
   this.index = index;
  }

  public int getIndex() {
   return this.index;
  }
 }

 public static void main(String args[]) {
   //Assume that day is passed as a argument
   String day = args[0];
   System.out.println("Entered valye of day is - " + day);
   System.out.println("Index of the day is - " + daysofweek.valueOf(day.toUpperCase()).getIndex());
 }
}

This is very similar to using the MAP but I think this prove more advantageous when we have more properties OR attributes for each enumerated element (in this case day).
Additionally see the use of “valueOf()” function. We can easily convert the input value to corresponding Enumerated constant.

Let’s say that we want to designate each day to represent task done on that day.
For e.g: Monday is SchoolDay, Tuesday is StoryTimeDay, Wednesday is SwimmingDay etc.
The enumeration above can be easily extended to accomodate this and ready to use instead of conditional statement in your code to handle this.

Modified Enum will look as below:


public class EnumTest {
 enum daysofweek {
  MONDAY(1,"Schoolday"),
  TUESDAY(2,"StoryTimeday"),
  WEDNESDAY(3,"Swimmingday"); //Not all the days are shown here

  private int index;
  private String activity;

  daysofweek(int index,String activity) {
    this.index = index;
    this.activity = activity;
  }

  public int getIndex() {
   return this.index;
  }

  public String activity() {
   return this.activity;
  }
 }

 public static void main(String args[]) {
  //Assume that day is passed as a argument
  String day = args[0];
  System.out.println("Entered valye of day is - " + day);
  System.out.println("Index of the day is - " + daysofweek.valueOf(day).getIndex());
  System.out.println("Activity for the day is - " + daysofweek.valueOf(day).activity());
 }
}

Do let me know your comments and suggestions about this one.

Cheers !!

Amit

Advertisements

2 Responses to Using Java Enums to replace conditional (IF) statements.

  1. andresinopz89 says:

    What is the best performance option of the above options?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: