DEV Community

Tuan
Tuan

Posted on

Refactor "switch" statements in case have large sets of "case" clauses

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

public class SwitchRefactor {

    // Define actions for each case
    private static final Map<String, Consumer<String>> ACTION_MAP = new HashMap<>();

    static {
        ACTION_MAP.put("case1", SwitchRefactor::actionForCase1);
        ACTION_MAP.put("case2", SwitchRefactor::actionForCase2);
        // Add more cases as needed
    }

    // Method for executing action for case 1
    private static void actionForCase1(String param) {
        System.out.println("Executing action for case 1 with parameter: " + param);
    }

    // Method for executing action for case 2
    private static void actionForCase2(String param) {
        System.out.println("Executing action for case 2 with parameter: " + param);
    }

    // Method for executing actions based on the given case
    public static void executeAction(String caseValue, String param) {
        Consumer<String> action = ACTION_MAP.get(caseValue);
        if (action != null) {
            action.accept(param);
        } else {
            System.out.println("No action found for case: " + caseValue);
        }
    }

    public static void main(String[] args) {
        // Example usage
        String caseValue = "case1";
        String param = "example";
        executeAction(caseValue, param); // Output: Executing action for case 1 with parameter: example
    }
}

Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook