how to eliminate multiple if statements?

Started by
9 comments, last by alnite 12 years, 8 months ago
For the sake of simplicity, I am going to assume that your actions are String objects. If you want to make your own Action class with customized parameters, that's up to you. But here it is:


public interface ActionHandler {
public void onAction(String a);
}

Hashtable<String, ActionHandler> actionsMap = new Hashtable<String, ActionHandler>();

/* somewhere where you define the actions and handlers */
actionsMap.put("walk", new ActionHandler {
public void onAction(String a) {
// do something here when user execute 'walk' command
}
});
actionsMap.put("talk", new ActionHandler {
public void onAction(String a) {
// do something here when user execute 'talk' command
}
});
... do more for other actions


/* somewhere where you execute the actions */
public void executeAction(String action) {
ActionHandler handler = actionsMap.get(action);
if (handler != null) {
handler.onAction(action);
}
}



Thanks to Java anonymous class, you don't actually need an if statement for each action, as it has its own implementation.


However, if you do decide that all your actions should be handled by one class, then you still need to do if statements. For example:


public class SomeClass implements ActionHandler {
public void onAction(String action) {
if (action.equals("walk")) {
// do something for walk
} else if (action.equals("talk")) {
// do something for talk
}
}
}

This topic is closed to new replies.

Advertisement