What is an appropriate data structure and database schema to store logic rules?

前端 未结 3 1311
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 13:56

Preface: I don\'t have experience with rules engines, building rules, modeling rules, implementing data structures for rules, or whatnot. Therefore, I don\'t know what I\'m doin

3条回答
  •  太阳男子
    2021-02-05 14:40

    Personally I would do this in code, not in SQL. Each item should be its own class implementing an interface (i.e. IItem). IItem would have a method called OkToPurchase that would determine if it is OK to purchase that item. To do that, it would use one or more of a collection of rules (i.e. HasPreviouslyPurchased(x), CurrentlyOwns(x), etc.) that you can build.

    The nice thing is that it is easy to extend this approach with new rules without breaking all the existing logic.

    Here's some pseudocode:

    bool OkToPurchase()
    {
       if( HasPreviouslyPurchased('x') && !CurrentlyOwns('y') )
           return true;
       else
           return false;
    }
    
    bool HasPreviouslyPurchased( item )
    {
        return purchases.contains( item )
    }
    
    bool CurrentlyOwns( item )
    {
        return user.Items.contains( item )
    }
    

提交回复
热议问题