The Expression Evaluator is designed to evaluate expressions with binary operators. The Expression Evaluator contains mainly four classes:
ExpTreeNode, and the
ExpEvaluator class has a has-a relationship with the
ExpEvaluator evaluates the expression with the help form
ExpParser, and the
IOperatorImp.ExpParser is the class where the parsing of the expression is being done. It derives from the interface
IParser. The expression tree and stack is being used in expressing the expression in the program. The
ExpParser parses the expression and returns the
ExpTreeNode type of the object, which then
ExpEvaluator uses to evaluate the expression.
ExpTreeNode follows the composite pattern.
ExpParser has been written to support the symbols in the expression.
The role of the
IOperatorImp in the design is to provide the meaning of the operators used in an expression. It derives from the
IOperator interface. Client is supposed to first create the parser that it wants to use to parse the expression. The parser should be derived from the
IParser. If the client does not provide the
ExpEvaluator will use the default implementation of the
IParser, i.e., the Infix Parser. The client also needs to provide the
IOperator implantation object to the
ExpEvaluator which it will use to calculate the expression. Same as Parser, if the client does not provide the implementation, the
ExpEvaluator will use default
IOperator implementation. For error handling, the
ErrorException class has been written.
We can also set the priority of the operator with respect to the others. In case of the same priority, the left to right evaluation happens. But then that can be easily implemented. By implementing the
IOperator interface, user can give their own meaning to the operators. By implementing the
IParser, user can parse the postfix and prefix expressions also. This design also provides the user to register their own Tokens and the Type they want them to be recognized. Symbols are allowed in the Expression. The value of the Symbol can be as indexed property of the Evaluator. One disadvantage that I see here in this design is if the user is implementing the parser, he is restricted to return the
ExpTreeNode to the Evaluator. That can also be omitted if we define the
IExpEnumerator interface which provides all the function that a parsed return object to the
ExpEvaluator should have. A little change in the design will solve this problem.
Usage of the Exp EVALUATOR
IParser par = new ExpParser();
ExpEvaluator eu = new ExpEvaluator(par);
double res =eu.Evaluate();
Users can also use the Symbols here. Expressions like "x+(1/y)+z" can also be solved. User need to provide the value of the Symbols like: