kesh kesh - 11 months ago 41
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) {
triggerContext = new TriggerContext(new DashboardTriggerHandler());
return triggerContext;
triggerContext = new TriggerContext(new ComponentTriggerHandler());
return triggerContext;
triggerContext = new TriggerContext(new WidgetTriggerHandler());
return triggerContext;



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 Source

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: