How to implement a rule engine?

后端 未结 10 1966
借酒劲吻你
借酒劲吻你 2020-11-27 23:58

I have a db table that stores the following:

RuleID  objectProperty ComparisonOperator  TargetValue
1       age            \'greater_than\'             15
2          


        
10条回答
  •  星月不相逢
    2020-11-28 00:36

    Reflection is your most versatile answer. You have three columns of data, and they need to be treated in different ways:

    1. Your field name. Reflection is the way to get the value from a coded field name.

    2. Your comparison operator. There should be a limited number of these, so a case statement should handle them most easily. Especially as some of them ( has one or more of ) is slightly more complex.

    3. Your comparison value. If these are all straight values then this is easy, although you will have divide the multiple entries up. However, you could also use reflection if they are field names too.

    I would take an approach more like:

        var value = user.GetType().GetProperty("age").GetValue(user, null);
        //Thank you Rick! Saves me remembering it;
        switch(rule.ComparisonOperator)
            case "equals":
                 return EqualComparison(value, rule.CompareTo)
            case "is_one_or_more_of"
                 return IsInComparison(value, rule.CompareTo)
    

    etc. etc.

    It gives you flexibility for adding more options for comparison. It also means that you can code within the Comparison methods any type validation that you might want, and make them as complex as you want. There is also the option here for the CompareTo to be evaluated as a recursive call back to another line, or as a field value, which could be done like:

                 return IsInComparison(value, EvaluateComparison(rule.CompareTo))
    

    It all depends on the possibilities for the future....

提交回复
热议问题