Long list of if statements in Java
using Command pattern:
public interface Command {
void exec();
}
public class CommandA() implements Command {
void exec() {
// ...
}
}
// etc etc
then build a Map<String,Command>
object and populate it with Command
instances:
commandMap.put("A", new CommandA());
commandMap.put("B", new CommandB());
then you can replace your if/else if chain with:
commandMap.get(value).exec();
EDIT
you can also add special commands such as UnknownCommand
or NullCommand
, but you need a CommandMap
that handles these corner cases in order to minimize client's checks.
My suggestion would be a kind of lightweight combination of enum and Command object. This is an idiom recommended by Joshua Bloch in Item 30 of Effective Java.
public enum Command{
A{public void doCommand(){
// Implementation for A
}
},
B{public void doCommand(){
// Implementation for B
}
},
C{public void doCommand(){
// Implementation for C
}
};
public abstract void doCommand();
}
Of course you could pass parameters to doCommand or have return types.
This solution might be not really suitable if the implementations of doCommand does not really "fit" to the enum type, which is - as usual when you have to make a tradeoff - a bit fuzzy.