{"id":51,"date":"2024-07-12T15:15:02","date_gmt":"2024-07-12T13:15:02","guid":{"rendered":"https:\/\/mesbahi.net\/en\/?p=51"},"modified":"2024-07-12T15:15:37","modified_gmt":"2024-07-12T13:15:37","slug":"expression-trees-2-creating-a-business-rule-engine","status":"publish","type":"post","link":"https:\/\/mesbahi.net\/en\/2024\/07\/12\/expression-trees-2-creating-a-business-rule-engine\/","title":{"rendered":"Expression Trees 2: Creating a Business Rule Engine"},"content":{"rendered":"\n<p id=\"ember1383\">In the <a href=\"https:\/\/www.linkedin.com\/pulse\/expression-trees-1-big-picture-amin-mesbahi-qddof\/?trackingId=aEvnS9HIRma4Vlh40eG3SQ%3D%3D\">previous post<\/a>, I covered the basics of expression trees, including their structure and how to create them in .NET. Now, let&#8217;s dive into a real-world example: building a simple Business Rule Engine (BRE) using expression trees. This engine will apply discount rules based on certain conditions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ember1384\">Scenario: Discount Calculation<\/h3>\n\n\n\n<p id=\"ember1385\">Imagine you are working on an e-commerce platform, and you need to implement a business rule engine (BRE) system, and one of its features is to calculate discounts based on various business rules. These rules might include conditions like:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If the customer is a premium member AND the order amount is greater than $100, apply a 10% discount.<\/li>\n\n\n\n<li>If the order contains more than 5 items OR the order amount is greater than $200, apply a 5% discount.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ember1387\">Building the Business Rule Engine<\/h3>\n\n\n\n<p id=\"ember1388\">We&#8217;ll build a <strong>modular <\/strong>Business Rule Engine that evaluates these conditions dynamically using expression trees. (using expressions, we can make cleaner, more maintainable, and performant code)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ember1389\">Step 1: Define the Data Model<\/h3>\n\n\n\n<p id=\"ember1390\">First, let&#8217;s define our data model for orders and customers.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Order\n{\n    public decimal Amount { get; set; }\n    public int ItemCount { get; set; }\n    public bool IsPremiumMember { get; set; }\n} <\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ember1391\">Step 2: Define the Rule Structure<\/h3>\n\n\n\n<p id=\"ember1392\">Next, we&#8217;ll define the structure for our discount rules.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class DiscountRule\n{\n    public Expression&lt;Func&lt;Order, bool&gt;&gt; Condition { get; set; }\n    public decimal DiscountPercentage { get; set; }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ember1393\">Step 3: Create the Rule Engine<\/h3>\n\n\n\n<p id=\"ember1394\">We&#8217;ll create a class to manage and evaluate these rules.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class RuleEngine\n{\n    private readonly List&lt;DiscountRule&gt; _rules = new List&lt;DiscountRule&gt;();\n\n    public void AddRule(DiscountRule rule)\n    {\n        _rules.Add(rule);\n    }\n\n    public decimal CalculateDiscount(Order order)\n    {\n        foreach (var rule in _rules)\n        {\n            var compiledCondition = rule.Condition.Compile();\n            if (compiledCondition(order))\n            {\n                return rule.DiscountPercentage;\n            }\n        }\n        return 0;\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ember1395\">Step 4: Define the Discount Rules<\/h3>\n\n\n\n<p id=\"ember1396\">Now let&#8217;s define our discount rules using expression trees.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\nusing System.Linq.Expressions;\n\nclass Program\n{\n    static void Main()\n    {\n        var ruleEngine = new RuleEngine();\n\n        \/\/ Rule 1: If the customer is a premium member AND the order amount is greater than $100, apply a 10% discount.\n        var rule1 = new DiscountRule\n        {\n            Condition = order =&gt; order.IsPremiumMember &amp;&amp; order.Amount &gt; 100,\n            DiscountPercentage = 10\n        };\n\n        \/\/ Rule 2: If the order contains more than 5 items OR the order amount is greater than $200, apply a 5% discount.\n        var rule2 = new DiscountRule\n        {\n            Condition = order =&gt; order.ItemCount &gt; 5 || order.Amount &gt; 200,\n            DiscountPercentage = 5\n        };\n\n        ruleEngine.AddRule(rule1);\n        ruleEngine.AddRule(rule2);\n\n        \/\/ Example order\n        var order = new Order\n        {\n            Amount = 150,\n            ItemCount = 3,\n            IsPremiumMember = true\n        };\n\n        decimal discount = ruleEngine.CalculateDiscount(order);\n        Console.WriteLine($\"Discount: {discount}%\"); \/\/ Output: Discount: 10%\n    }\n} <\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ember1397\">Benefits of Using Expression Trees<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Flexibility<\/strong>: Easily define and modify business rules without changing the core logic.<\/li>\n\n\n\n<li><strong>Dynamic Evaluation<\/strong>: Compile and evaluate conditions at runtime.<\/li>\n\n\n\n<li><strong>Modularity<\/strong>: Add or remove rules as needed without affecting other parts of the system.<\/li>\n\n\n\n<li><strong>Performance:<\/strong> A compiled code can be run faster<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"ember1399\">Conclusion<\/h3>\n\n\n\n<p id=\"ember1400\">By leveraging expression trees, we can build a flexible and modular Business Rule Engine that dynamically evaluates complex conditions. This approach not only simplifies the implementation of business logic but also enhances maintainability and scalability.<\/p>\n\n\n\n<p id=\"ember1401\">Stay tuned!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the previous post, I covered the basics of expression trees, including their structure and how to create them in .NET. Now, let&#8217;s dive into a real-world example: building a simple Business Rule Engine (BRE) using expression trees. This engine will apply discount rules based on certain conditions. Scenario: Discount Calculation Imagine you are working &#8230; <a title=\"Expression Trees 2: Creating a Business Rule Engine\" class=\"read-more\" href=\"https:\/\/mesbahi.net\/en\/2024\/07\/12\/expression-trees-2-creating-a-business-rule-engine\/\" aria-label=\"Read more about Expression Trees 2: Creating a Business Rule Engine\">Read more<\/a><\/p>\n","protected":false},"author":2,"featured_media":52,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[10],"tags":[8,7,9],"class_list":["post-51","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-software-development","tag-c","tag-expression-tree","tag-software-engineering"],"uagb_featured_image_src":{"full":["https:\/\/mesbahi.net\/en\/wp-content\/uploads\/sites\/2\/2024\/07\/TfK7aYGATNqB279dheYGLQ.webp",1232,768,false],"thumbnail":["https:\/\/mesbahi.net\/en\/wp-content\/uploads\/sites\/2\/2024\/07\/TfK7aYGATNqB279dheYGLQ-150x150.webp",150,150,true],"medium":["https:\/\/mesbahi.net\/en\/wp-content\/uploads\/sites\/2\/2024\/07\/TfK7aYGATNqB279dheYGLQ-300x187.webp",300,187,true],"medium_large":["https:\/\/mesbahi.net\/en\/wp-content\/uploads\/sites\/2\/2024\/07\/TfK7aYGATNqB279dheYGLQ-768x479.webp",768,479,true],"large":["https:\/\/mesbahi.net\/en\/wp-content\/uploads\/sites\/2\/2024\/07\/TfK7aYGATNqB279dheYGLQ-1024x638.webp",1024,638,true],"1536x1536":["https:\/\/mesbahi.net\/en\/wp-content\/uploads\/sites\/2\/2024\/07\/TfK7aYGATNqB279dheYGLQ.webp",1232,768,false],"2048x2048":["https:\/\/mesbahi.net\/en\/wp-content\/uploads\/sites\/2\/2024\/07\/TfK7aYGATNqB279dheYGLQ.webp",1232,768,false]},"uagb_author_info":{"display_name":"Amin","author_link":"https:\/\/mesbahi.net\/en\/author\/en\/"},"uagb_comment_info":0,"uagb_excerpt":"In the previous post, I covered the basics of expression trees, including their structure and how to create them in .NET. Now, let&#8217;s dive into a real-world example: building a simple Business Rule Engine (BRE) using expression trees. This engine will apply discount rules based on certain conditions. Scenario: Discount Calculation Imagine you are working&hellip;","_links":{"self":[{"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/posts\/51","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/comments?post=51"}],"version-history":[{"count":1,"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/posts\/51\/revisions"}],"predecessor-version":[{"id":53,"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/posts\/51\/revisions\/53"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/media\/52"}],"wp:attachment":[{"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/media?parent=51"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/categories?post=51"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mesbahi.net\/en\/wp-json\/wp\/v2\/tags?post=51"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}