Monday, 12 August 2013

Enums and interfaces? Interesting connection

We often have to make a decision based on enum value. Usually it ends in long switch statement. What if I told you there is a better way to do this?

1. What do we want?


We want our enum to be self-describing and to achive this we created interface:

1
2
3
public interface SelfDescribing {
 String getDescription();
}


2. What do we have?


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public enum MessageType implements SelfDescribing {
 INFO, WARNING, ERROR;

 public String getDescription() {
  switch (this) {
  case ERROR:
   return "What do you want? Go fix your problem.";
  case INFO:
   return "Hi i'm INFO Message";
  case WARNING:
   return "Hi i'm WARNING Message";
  default:
   return null;
  }
 }
}


What we see here is switch statement. It's just ugly and after you add new message type you will have to remember about extending it. Compiler won't remind you about it.

3. What is more elegant solution?


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public enum MessageType implements SelfDescribing{
 INFO
 {
  public String getDescription() {
   return "Hi i'm INFO Message";
  }
  
 }, WARNING
 {
  public String getDescription() {
   return "Hi i'm WARNING Message";
  }
 }, ERROR
 {
  public String getDescription() {
   return "What do you want? Go fix your problem.";
  }
 };
}


It's cleaner, more focused on goal and less error-prone.