Tuesday, April 29, 2014

Programming things to remember 2014 Febr

Generic method for enums


For some reason (by the time, I'm writing this post, I've already forgotten) I created a class, that can extract an enum from an android Bundle (basically a Map of stuffs, in this case the stuff is String). I think the reason was to make this kind of operation easy. All the null checks are in one place, and it requires 2 lines of code to extract any enum from a bundle.

public class EnumFromBundleExtractor<T extends Enum<T>> {
    @Nonnull
    public T getValueFrom(Bundle savedInstanceState, @Nonnull String key, @Nonnull T defaultValue) {
        Preconditions.checkNotNull(key);
        Preconditions.checkNotNull(defaultValue);
        
        if (savedInstanceState == null) {
            return defaultValue;
        }
        
        final String bundledValueAsString = savedInstanceState.getString(key);
        if (bundledValueAsString == null) {
            return defaultValue;
        }
        
        try {
            return Enum.valueOf(defaultValue.getDeclaringClass(), bundledValueAsString);
        } catch (IllegalArgumentException iae) {
            return defaultValue;
        }
    }
}


Usage (VisualState is an enum):

final EnumFromBundleExtractor visualStateExtractor = new EnumFromBundleExtractor();
final VisualState visualState = visualStateExtractor.getValueFrom(savedInstanceState, BUNDLE_VISUAL_STATE_AS_ORDINAL, VisualState.INITIAL);

No comments: