Representing Logical Operations in an OO manner with Java

ε祈祈猫儿з 提交于 2019-12-11 06:06:53

问题


My java program will allow the content of a csv file to be filtered based on a user defined logical operation. Data will be read from the content of two column csv file

left    right
5       10
2       6

and user will provide a logical condition operation on the command line referencing left and right. The program should filter to content of the csv files based on the outcome of the logical operation.

IF ((left < right) AND (left !=10)) THEN 5 ELSE right 

I plan to represent the operation types as an enum

enum Operation
    >,
    <,
    ==,
    !=

 public boolean evaluate(int left,int right);

which would support an evaluate method. The specific logic for the operation would be implemented within the specific enum types.

A Condition interface would support methods to access the left operand, operation and right operand

interface Condition
{
    public int getLeft();
    public Operation();
    public int getRight();
}

For a AND case I would just maintain a list of Conditions and iterate over the list to ensure that all conditions are true. But how show i represent the IF THEN ELSE key words?


回答1:


Following your interface convention:

interface Conditional {
    public Condition Condition();
    public int TrueValue();
    public int FalseValue();
}

I would use classes and instead of referring to ints, I would refer to an Expression class too.




回答2:


How about rather than taking that approach you use something like Velocity? You basically read all the numbers in left in an array and all the numbers in right in a different array and pass these arrays to the Velocity context then let the user type a Velocity style if conditional and let Velocity take care of the rest ?



来源:https://stackoverflow.com/questions/6470046/representing-logical-operations-in-an-oo-manner-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!