java - Alternative to a very long switch-case statement -
i find myself in situation, have write java programm processes various methods in form of strings, after being scanned in. handle method, has pretty long switch-case statement processes method in form of string. not sure whether approach or not, think looks , behaves dirty, wanted ask if there better solution problem.
you can use map instead.
final map<string, consumer<string>> actionmap = new hashmap<>(); consumer<string> defaultaction = ... // add actions map actionmap.put("case 1", s -> { dosomething() }); actionmap.put("case 2", s -> { dosomething() }); actionmap.put("case 3", s -> { dosomething() }); // instead of switch string action = ... actionmap.getofdefault(action, defaultaction).apply(action);
with construct can lay out "switch" way wish, dynamically , across many methods/class/libraries.
Comments
Post a Comment