Re: Alternative to if...else for keyword based actions
c0balt279@gmail.com wrote:
I was wondering if there is an alternative to if...else and
switch(case) where you don't have to define the results. For example,
if the input "println Hello World;" is sent to the program where
println calls the method println(String str) with the parameter "Hello
World". I could use string tokenizer to separate the parts of the
word. Then looping through the tokens, I'd have to do a sequence of
if..else like
String token = "println";
String parameter = "Hello World";
if(token.equals("print")){
println(parameter);
}
else if(token.equals("add")){
add(parameter);
}
else if(token.equals("multiply")){
multiply(parameter);
}
else if(token.equals("divide")){
divide(parameter);
}
else if(token.equals("subtract")){
subtract(parameter);
}
else if(token.equals("println")){
println(parameter);
}
How can I override the condition check and directly call a method
based on a string name of the method?? I'm trying to create a program
that reads a notepad source file and executes a program based on it.
Having all of these if...else checks was really getting annoying. Help?
One way is to define a class for each of the actions you want
to take. Have all the action classes implement a common interface
(or extend a common superclass, probably an abstract class), and
put an instance of each in a Map keyed on the String you want:
interface Actionable {
public void act(String parameter);
}
Map<String,Actionable> dispatch = ...;
dispatch.put("print", new Actionable() {
public void act(String parameter) {
System.out.print(parameter);
}
});
dispatch.put("println", new Actionable() {
public void act(String parameter) {
System.out.println(parameter);
}
});
...
After initializing the Map, you can process the lines:
String token = ...;
String param = ...;
Actionable action = dispatch.get(token);
if (action != null)
action.act(param);
else
throw new BogusInputException();
You'll have to decide for yourself whether this is worth while.
It probably adds up to two or three times as much source, but it
offers a lot of flexibility: changing the suite of Actionables in
mid-stream, initializing them differently depending on preferences
or the phase of the moon, ...
--
Eric.Sosman@sun.com