Friday, September 14, 2012

Cool java enums

In this tutorial  I'm going to show you how cool the enums in java are.

So let's start wit standard java enum:



package com.examples.coolEnums;

public enum EnumExample {
     ENUM1,
     ENUM2,
     ENUM3        
}


now let's say you need this enum to be represented as integer in some transport protocol, since java does not provide standard mechanism to assign integer values for enums (as in C# ENUM1=1, ...).
Many developers therefore fall back to using constants, something like this:

package com.examples.coolEnums;

public class Constants {
  public static final int CONSTANT_1 = 1;
  public static final int CONSTANT_2 = 2;
  public static final int CONSTANT_3 = 3;

}

this is in general one of the possibilities, but you loose the advantage of type safety, compiler can't ensure in build time that the value assigned to some int variable is present in constants.
Let's take a different approach and spice things a little.
The way to do this is to define a constructor for the enum:


package com.examples.coolEnums;

public enum EnumExample {
     ENUM1(1),
     ENUM2(2),
     ENUM3(3);
     
     private int index;
     EnumExample(int intValue)
     {
       this.index = intValue;
     }
     
     public int intValue()
     {
       return this.index;
     }
}



this way, every enumeration has it's index value. You can access it by the intValue() method.

But what about the transformation of int to enum? Let's add a static method to EnumExample class:


public static EnumExample valueOf(int intCode)
  throws InvalidParameterException
{
  for(EnumExample code: EnumExample.values())
  {
    if (code.intValue() == intCode) {
            return code;
        }
  }

  throw new InvalidParameterException("No such code defined!");
}


you can extend the enum any way you want in a similar fashion. You could add compare methods, utils and many others.

The benefit of this approach is also that you still have the type safety ensured!