Java – is an if else tree the best approach in the following situations?
What am I doing:
I'm creating a simple calculator in Java that reads a string written in postfix notation (for example: 3, 4) It then accepts the string and reads it from left to right It stores every number it finds and then applies the following operators For example: 3 4 – > store 3, store 4, run 3 4 and store the results
What I need help with is:
How should characters and predefined operators be checked (if (C = = '/'), etc.) In my case, what are the alternatives to the if else tree? If I want to add new operators with minimal effort (and the lowest performance loss), which one should I choose What is generally considered good practice?
Solution
If you encapsulate operations as objects, you can usually replace switch like statements with data structures, and you want to add only operations in the future
For example, this is a way to encapsulate operations as objects: use enum to represent operations:
http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html
public enum Operation { PLUS { double eval(double x,double y) { return x + y; } },MINUS { double eval(double x,double y) { return x - y; } },TIMES { double eval(double x,double y) { return x * y; } },DIVIDE { double eval(double x,double y) { return x / y; } }; // Do arithmetic op represented by this constant abstract double eval(double x,double y); }
You can extend this example to associate symbols with each operation and provide static methods to find operations associated with symbols [[I'm torn between this mixed UI / view code and logic / domain code, but you mentioned that you want simplicity, so maybe it's good for your program.]]
If you encapsulate operations as objects, you can consider using data structures to replace code similar to exchange:
>If there are many operations, consider building a HashMap to map symbols to operations. > If there are a few operations, it may be cheap enough to have a collection of all operations and simply traverse all operations to ask if each operation works on a user supplied symbol and use the first found operation