public enum Type {
DEBIT,
CREDIT;
public static Map<String, Type> typeMapping = Maps.newHashMap();
static {
typeMapping.put(DEBIT.name(), DEBIT);
typeMapping.put(CREDIT.name(), CREDIT);
}
public static Type getType(String typeName) {
if (typeMapping.get(typeName) == null) {
throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
}
return typeMapping.get(typeName);
}
}
I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.
Enum BestEnumEver {OPTION_A, OPTION_B, OPTION_C}
// ... elsewhere in your code ...
// How confident are you that stringVar will have an acceptable value?
// How confident are you that the existing enum options will not need to change?
BestEnumEver enumValue;
try {
// Consider using trim to eliminate extraneous whitespace
enumValue = BestEnumEver.valueOf(stringVar.trim());
} catch (Exception e) {
// handle the situation here. Here are a couple of ideas.
// Apply null and expect the using code to detect.
enumValue = null;
// Have a defined private constant for a default value
// assuming a default value would make more sense than null
enumValue = DEFAULT_BEST_ENUM_EVER;
}
But you could also handle each exceptions in some unique way.
Enum BestEnumEver {OPTION_A, OPTION_B, OPTION_C}
// ... elsewhere in your code ...
// How confident are you that stringVar will have an acceptable value?
// How confident are you that the existing enum options will not need to change?
BestEnumEver enumValue;
try {
// Consider using trim to eliminate extraneous whitespace
enumValue = BestEnumEver.valueOf(stringVar.trim());
} catch (IllegalArgumentException e1) {
// handle the situation here ...
} catch (NullPointerException e2) {
// handle the situation here ...
}