Reputation: 189
I have 2 files: ImplementationProvider and CaseHandler.
ImplementationProvider:
class ImplementationProvider {
public void method1(Object[] params) {}
public void method2(Object[] params) {}
...
public void method100(Object[] params) {}
}
CaseHandler:
class CaseHandler {
ImplementationProvider ip; // auto injected
public void handle(String s, String param) {
switch(s) {
case USE_CASE_ONE: ip.method1(param); break;
case USE_CASE_TWO: ip.method2(param); break;
...
}
}
}
How can I refactor the CaseHandler so that the USE_CASE strings are keys in a HashMap where the values would be the methods? The main issue I'm having is the propagation of the parameters. Other answers here recommend using an interface, however I need to provide the parameter on runtime.
Upvotes: 4
Views: 9458
Reputation: 393986
Here's one way I can think of, using the Consumer
functional interface:
Map<String,Consumer<Object[]>> methods = new HashMap<>();
methods.put (USE_CASE_ONE, param -> ip.method1(param));
methods.put (USE_CASE_TWO, param -> ip.method2(param));
...
public void handle(String s, String param) {
methods.get(s).accept(new Object[]{param});
}
EDIT:
If your methods require two parameters, you can use the BiConsumer
interface:
Map<String,BiConsumer<String,List<String>>> methods = new HashMap<>();
methods.put (USE_CASE_ONE, (s,l) -> ip.method1(s,l));
methods.put (USE_CASE_TWO, (s,l) -> ip.method2(s,l));
...
public void handle(String s, String param) {
methods.get(s).accept(someString,someListOfStrings);
}
Upvotes: 3
Reputation: 48434
If you are using Java 8, you can lever the Consumer
functional interface to parametrize your map's values with.
Example:
private static Map<String, Consumer<String>> MAP = new HashMap<>();
static {
MAP.put("USE_CASE_ONE", (s) -> {/*TODO something with param s*/});
// etc.
}
... then somewhere else:
public void handle(String key, String param) {
// TODO check key exists
MAP.get(key).accept(param);
}
What happens here is that for each given key set entry, you map it with a function that consumes a String
(your param
).
Then, you invoke the Consumer
's accept
on your given param in one line.
Upvotes: 2