kesh kesh - 3 months ago 10
Java Question

Make code more Generic in Java

I have a Trigger Manager scenario where I delegate the triggers (in other-words subscribe triggers) to different handlers.

For now I have three handler types, I use a switch-case with enum (enum here is the handler type) to redirect to correct handler.

But my code seems not extensible, its not generic and it doesn't follow SOLID principle. Imagine if I need to have more handler

I will be eventually coming and editing my switch case code and I will have more cases where it affects the cyclomatic complexity of my code

Below is my exact code snippet

private static TriggerContext getTriggerContext(TriggerHandlerType triggerHandlerType) throws TriggerHandlerException {
switch (triggerHandlerType) {
case DASHBOARD_HANDLER:
triggerContext = new TriggerContext(new DashboardTriggerHandler());
return triggerContext;
case COMPONENT_HANDLER:
triggerContext = new TriggerContext(new ComponentTriggerHandler());
return triggerContext;
case WIDGET_HANDLER:
triggerContext = new TriggerContext(new WidgetTriggerHandler());
return triggerContext;
default:
LOGGER.error(MIS_CONFIGURED_REQUEST_IS_PROVIDED);
throw new TriggerHandlerException(TRIGGER_HANDLER_TYPE_GIVEN_IS_NOT_CONFIGURED_IN_THE_LIST_OF_TRIGGER_HANDLERS);

}

}


Can someone help me to enhance this code in-which I can make it more generic and avoid cyclomatic complexity and follow SOLID Principle along with some design pattern.

Answer

One of the solution is to use polymorphism to handle triggers differently. For instance, you could declare the Trigger interface and have several implementations. In this case, when you need a new trigger type, you just implement this interface and don't touch the existing code:

Comments