CleanCode logo
NAVIGATION: first page in sectionprevious pageup one levelnext pagefinal page in section

Guideline IF2: Avoid multiple if-then-else with dynamic lookup switching

We've covered switch statements and static lookup tables in IF1. For completeness, we'll mention dynamic lookup tables, but the treatment here is fairly elementary. Dynamic method lookup is a powerful capability in Java, but it does incur some overhead. What it provides, however, is the ability to invoke a method just by its string name. One could, then, ask a user to type in a method name, and then the program could execute that method. The example below provides one example of a basic skeleton to invoke a method dynamically. This code snippet requires that you set up action commands on events which trigger the ActionListener containing this actionPerformed handler. The event message is then passed to the method after the method is looked up by name.

Instead of:
private final String CMD_REFRESH = "doRefresh";
private final String CMD_CLEAR_HISTORY = "doClear";
private final String CMD_COPY_TAB= "doCopyTab";
private final String CMD_PASTE_COOKIE = "doPasteCookie";
private final String CMD_SAVE_HISTORY = "doSaveHistory";
. . .

public void actionPerformed(ActionEvent event) {
	String cmd = event.getActionCommand();
	if      (cmd.equals(CMD_REFRESH))       { doRefresh(event); }
	else if (cmd.equals(CMD_CLEAR_HISTORY)) { doClear(event); }
	else if (cmd.equals(CMD_COPY_TAB))      { doCopyTab(event); }
	else if (cmd.equals(CMD_PASTE_COOKIE))  { doPasteCookie(event); }
	else if (cmd.equals(CMD_SAVE_HISTORY))  { doSaveHistory(event); }
	. . .
public void actionPerformed(ActionEvent event) {
	String cmd = event.getActionCommand();
	try {
		Method m = this.getClass().getMethod(
			cmd, new Class[] { ActionEvent.class });
		m.invoke(this, new Object[] { event });
	catch (Exception exc) { ... }
Valid XHTML 1.0!Valid CSS!Get CleanCode at Fast, secure and Free Open Source software downloads
Copyright © 2001-2013 Michael Sorens • Contact usPrivacy Policy
Usage governed by Mozilla Public License 1.1 and CleanCode Courtesy License
CleanCode -- The Website for Clean DesignRevised 2013.06.30