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

tuannguyen_talan

Tuan

Posted on March 9, 2024

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
💖 💪 🙅 🚩
tuannguyen_talan
Tuan

Posted on March 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related