When developing in any language, enumeration classes are a wonderful tool to not only promote readability but to also make your code much more maintanable. The following is an example of an enumeration class design that I have used over and over. It allows for different representations of the enumeration and also provides conversion methods to go from code or displayString to enumeration. Notice that the conversion methods (getValueFromDisplayString,getValueContainsFromDisplayString,getEnumFromCode) do not reference any enum values directly. This means that if you want to add a new enumeration to the list, you simply have to add it to the enumeration declaration and all other interfaces will work as expected.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public enum AcronymEnum {
AFK("AFK", "Away from keyboard"),
BRB("BRB","Be right back"),
BBIAB("BBIAB","Be back in a bit"),
BBL("BBL","Be back later"),
NONE("NONE","None"),
INVALID("INVALID", "Invalid");
private String code;
private String displayString;
private AcronymEnum(String code, String displayString)
{
this.code = code;
this.displayString = displayString;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public String getDisplayString()
{
return displayString;
}
public void setDisplayString(String displayString)
{
this.displayString = displayString;
}
@Override
public String toString()
{
return code;
}
public static AcronymEnum getValueFromDisplayString( String displayString )
{
if(StringUtils.isEmpty(displayString))
{
return AcronymEnum.NONE;
}
List<AcronymEnum> enumList = Arrays.asList(AcronymEnum.values());
AcronymEnum enumeration = enumList
.stream()
.filter(enumValue -> displayString.equalsIgnoreCase(enumValue.getDisplayString()))
.findFirst()
.orElse(AcronymEnum.INVALID);
return enumeration;
}
public static AcronymEnum getValueContainsFromDisplayString(String displayString)
{
if(StringUtils.isEmpty(displayString))
{
return AcronymEnum.NONE;
}
List<AcronymEnum> enumList = Arrays.asList(AcronymEnum.values());
AcronymEnum enumeration = enumList
.stream()
.filter(enumValue -> StringUtils.containsIgnoreCase(displayString,enumValue.getDisplayString()))
.findFirst()
.orElse(AcronymEnum.INVALID);
return enumeration;
}
public static AcronymEnum getEnumFromCode( String code )
{
if(StringUtils.isEmpty(code))
{
return AcronymEnum.NONE;
}
List<AcronymEnum> enumList = Arrays.asList(AcronymEnum.values());
AcronymEnum enumeration = enumList
.stream()
.filter(enumValue -> code.equalsIgnoreCase(enumValue.getCode()))
.findFirst()
.orElse(AcronymEnum.INVALID);
return enumeration;
}
}