Search code examples
javaenumsjava-8solid-principles

Is it good to have enum implementation with processing logic?


In the below example Enums do the amount of processing that a class would do.

enum TriggerHandlerType {
    DASHBOARD {
        @Override
        TriggerHandler create() {
            return new DashboardTriggerHandler();
        }
    },
    COMPONENT_HANDLER {
        //...
    };

    abstract TriggerHandler create();
}

private static TriggerContext getTriggerContext(TriggerHandlerType triggerHandlerType) throws TriggerHandlerException {
    return new TriggerContext(triggerHandlerType.create());
}

Enums are usually used for type safe storage of constants where as in this case they will be returning varying values based on the processing logic. In a way its seems to be a comprehensive technique as the Enums here do the state determination themselves which eases the processing of classes. Also since the return values are a subset of finite values, it seems to make some sense to have the processing handled by the Enums themselves.

I do see problem here where this will break the Open-Close principle in SOLID and the class will have increment in lines of code whenever more enums get added, Could anyone share your thoughts on this?


Solution

  • I had an enum as such, doing operations like OR, AND, SEQ and such.

    With java 8 and just one overriden method you could also make a constructor with a functional interface as parameter.

    enum TriggerHandlerType {
        DASHBOARD(() -> DashboardTriggerHandler::new)),
        COMPONENT_HANDLER (() -> { ... });
    
        private final Fun fun;
    
        private TriggerHandlerType(Fun fun) {
            this.fun = fun;
        }
    
        public TriggerHandler create() {
            fun.apply();
        }
    }
    

    In an other case I did not use this technique, to decouple classes, and have clear tiers of classes. The enum was an early class not already using later classes.

    A Map from enum to handler would be OO too. A unit test might check that the created map has a size equal to the enum values'.

    I need not say, that enum is an artificial coupling. Fixed number of elements or not, one could make separate classes/singletons.

    so it depends.