vendredi 19 août 2016

How to avoid switch-case statements in Java

I have an enum of TriggerType, where different triggers can be added

public enum TriggerType {
    meta,data,list,toggle
}

These trigger types are used inside different handlers (eg Component, Dashboard etc) to identify which trigger is triggered inside the handler through a switch-case, for eg Code snippet of ComponentHandler using trigger through switch-case is given below

@Override
public TriggerResultInterface executeTriggerJob(TriggerEventHelper triggerEventHelper) throws TriggerHandlerException {
    switch (triggerEventHelper.getTriggerName()) {
        case meta:
            return getMetaComponentConfig(triggerEventHelper);
        case data:
            return getComponentData(triggerEventHelper);
        default:
            LOGGER.debug(INVALID_TRIGGER_NAME_CONFIGURED);
            throw new TriggerHandlerException(INVALID_TRIGGER_NAME_CONFIGURED);
    }

}

Imagine If I want to add a new Trigger, I have to update the enum class which is unavoidable, at the same time I have to update each of my handler classes which that Trigger need to be used, Is this way of design with coding is good or is there any-other better solution that will enhance this code and follows SOLID principles along with a better design.

Aucun commentaire:

Enregistrer un commentaire