I have this class that contains four private methods, with same two arguments each, and a public method which chooses between them. The possible methods are stored in a Map and more may be added. I would like to dynamically call the proper method, removing the switch..case. Is there a polite way to do it, i.e. without getMethod/invoke?
public class PlayerClass {
private MediaSource customPlayFunction1(Channel chn, OtherParam other) {
}
private MediaSource customPlayFunction2(Channel chn, OtherParam other) {
}
private MediaSource customPlayFunction3(Channel chn, OtherParam other) {
}
private MediaSource defauPlayFunction(Channel chn, OtherParam other) {
}
public void playChannel(Activity activity, Channel chn) {
//do something
switch (chn.customFunction) {
case ("CustomPlayFunction1"): {
videoSource = customPlayFunction1(chn,other);
break;
}
case ("CustomPlayFunction2"): {
videoSource = customPlayFunction2(chn,other);
break;
}
case ("CustomPlayFunction3"): {
videoSource = customPlayFunction3(chn,other);
break;
}
default: {
videoSource = defaultPlayFunction(chn,other);
break;
}
}
//do something else
}
}
play(...)method - extract the handler-methods in separate handler-classes, implementing the interface - select the appropiate hander class, based on thecustomFunction. Notice that the interface would have someboolean handles(String customFunction)-method to select the appropiate concrete implementation to select.Map<String, BiFunction>where you insertkey = "CustomPlayFunction1" (string), value = customPlayFunction1 (method). Which is essentially just another form of switch-case. But I doubt that this will make your code easier / smaller / faster.