Business Rule Evaluation
Rule Elements and Definitions
Code Effects decision automation platform supports two types of business rules: evaluation type and execution type. The evaluation type only answers one question — True or False. The execution type answers the same question and also can invoke public methods and/or set/update field values. Here are examples of both rule types:
Check if First Name is equal to "John" and Age is greater than or equal to 18
If First Name is equal to "John" and Age is greater than or equal to 18 then set Email to "john@test.test" and Send Notification (Email, "Hello!")
Notice how you were able to read both Code Effects rules and immediately understand the business logic each rule defines without the necessity of deciphering or decoding any cryptic format or decision table.
In both rules the First Name is equal to "John" and the Age is greater than or equal to 18 are called conditions. Each condition consists of a field, an operator, and a value. Both the field and the value can be either a property of your source object or a qualified in-rule method declared anywhere. The value can also contain user input, or be expressed as a numeric calculation, as a concatenation of strings, or, for a date, as another date shifted by a number of days, months, or years.
Not every condition has exactly one value. Is between and Is not between take two values and include both of them, Is in and Is not in take a list of values, and Has no value and Has any value take none; see Operators. A condition can also be about a collection of the source object: the Collections... menu checks whether any item, no item or every item matches conditions of its own (Exists, Does not exist, All), looks at the first or the last item, or counts the items, all of them or the ones that match; see Collections. All is false for an empty collection, so a rule never passes because there was nothing to check.
The execution type rule can have one or more rule sections. Each section starts with a flow element: If, Else If, or Else:
If Phone starts with "770" then set State to Georgia
Else if Phone starts with "215" then set State to Pennsylvania
Else if Phone starts with "212" then set State to New York
Else set State to Unlisted
The rule above has four sections. The execution type rules must begin with the If section, can have none or many Else If sections, and may have only one Else section. The evaluation type rules can only have one section that starts with the flow element Check if.
Sections Check if, If, and Else If can have as many conditions as needed. The If and Else If sections must end with the Then action clause that encapsulates setters and/or rule actions. The Else section cannot have conditions and must only contain setters and/or actions. Rule sections may have any number of setters and action methods in any order. Setters and action methods are invoked in the order they are referenced in the rule during rule evaluation.
Two modes of the Rule Editor change this structure. In the Ruleset mode a rule can have any number of If sections that do not depend on each other, and the engine evaluates them one after another; see Rule Evaluation below. In the Loop mode the rule has a single section that the engine evaluates repeatedly until it returns true.
Rule conditions may have one or more logical levels divided by logical operators and or or. A level is a collection of rule conditions combined under the same logical operator. Code Effects employs parentheses to split rules into logical levels. They are unique to Code Effects platform.
Check if Street is "123 Main Dr" and (Zip Code is "30004" or Zip Code is "30005")
The rule above has two logical levels — the higher one under the and operator, and the lower one under the or operator. Both levels contain two conditions (the or level is the second condition for the and level). Both rule types may have as many nested logical levels as needed, and each level may have one or more conditions.
One feature that is also unique to Code Effects is Reusable Rules, which allow you to use any evaluation type rule in any other rules as if it were a Boolean field. For example, if we save the following rule under the name Adult:
Check if Age is greater than or equal to 18
... and tell the editor to use it in field menus:
using System.Collections.Generic;
using CodeEffects.Rule.Editor;
using CodeEffects.Rule.Editor.Models;
var editor = new Control("divEditorId");
editor.ContextMenuRules = new List<MenuItem>
{
new MenuItem
{
ID = "GuidID",
DisplayName = "Adult"
}
};
... we can create rules like these two reusing the same logic:
Check if Gender is Female and Adult is True
If Adult is True and Has Account ( Checking ) is False then Send Invitation
An execution type rule can also run other execution type rules from its Then and Else clauses with the Execute... item, the rules that you list in the InlineRules property of the control. The executed rule is evaluated in place and in order, against the same object, so it sees the values that the rule has already set. A rule that executes itself, directly or through other rules, is refused when the evaluator is built (control number GH7427).
The evaluator needs to find the rules that a rule reuses or executes. Give it a function that takes a rule ID and returns that rule's Rule XML, through the RuleResolver property of the EvaluationParameters class. If you use the Rule Repository, no resolver is needed: Context.GetRules(..), or Audit's GetRules(..), returns the live version of each rule you ask for together with the live versions of every rule it calls, as one ruleset ready for the evaluator. See Evaluating Rules from the Repository, which also explains when to load the rules again after a new version goes live.
Rule Evaluation
By default, the evaluator stops evaluating a rule as soon as the result is known. Inside a section, conditions under an or operator are evaluated until the first one returns true, and conditions under an and operator until the first one returns false; the rest are not evaluated at all, so an in-rule method that the later conditions call is not invoked. The execution rule also invokes its setters and actions and waits for them to complete before returning the result of its evaluation.
In a rule with If, Else If, and Else sections, only the first section whose conditions are true is executed. Consider the following four sections:
If Name is "John" then Action 1
Else if Name is "Alex" or Email ends with "hotmail.com" then Action 2
Else if Name is "Michael" or Email contains "gmail" then Action 3
Else Action 4
If the Name value of the record being evaluated against this rule is John, the rule invokes Action 1 and returns true. Actions 2, 3, and 4 never get hit, even if their conditions would return true as well. This is the meaning of Else, and nothing changes it.
Sometimes rules require greater control over the evaluation flow. When the Rule Editor is in the Ruleset mode, a rule can have several independent If sections, with no Else between them:
If Name is "John" then Action 1
If Name is "Alex" or Email ends with "hotmail.com" then Action 2
If Name is "Michael" or Email contains "gmail" then Action 3
The EvaluationParameters class defines what the engine does with them, with two properties:
Scope is EvaluationScope.All by default. The rule returns true only if every section returns true, and the engine stops at the first section that returns false. With EvaluationScope.AtLeastOne, the rule returns true if at least one section returns true, and the engine stops at the first that does.
ShortCircuit is true by default, which is what stops the engine as described. Set it to false, and all sections are evaluated and all setters and actions of every section that returns true are invoked, even if the result of the rule is already known.
The following code evaluates the three sections above against a customer whose name is John and whose email contains gmail. The Customer class declares Name and Email, and public methods Action1, Action2, and Action3 that the rule invokes as actions:
using CodeEffects.Rule.Common.Models;
using CodeEffects.Rule.Engine;
var rule = // Load XML of our rule from its storage
var customer = new Customer { Name = "John", Email = "test@gmail.com" };
var ev = new Evaluator(typeof(Customer), rule, new EvaluationParameters() { ShortCircuit = false });
bool result = ev.Evaluate(customer);
Actions 1 and 3 are invoked and Action 2 is not. The result is false, because the default scope requires every section to be true and the second section is not. With Scope = EvaluationScope.AtLeastOne, the result is true. With the default ShortCircuit of true, only Action 1 is invoked in both cases: with the default scope the engine stops at the second section, and with AtLeastOne it stops at the first.
Rulesets
As mentioned in Engine Implementation and Rule XML articles, rules can be combined into large rulesets if you need to evaluate any number of different rules referring to the same source object against the same set of data. That improves performance because all your rules are compiled only once:
<?xml version="1.0" encoding="utf-8"?>
<codeeffects
xmlns="https://codeeffects.com/schemas/rule/7"
xmlns:ui="https://codeeffects.com/schemas/ui/7">
<rule id="ID1" ...>
<!-- Rule #1 -->
</rule>
<rule id="ID2" ...>
<!-- Rule #2 -->
</rule>
<rule id="ID3" ...>
<!-- Rule #3 -->
</rule>
...
</codeeffects>
The Evaluate() method evaluates one rule of the ruleset: the first one by default, or the one whose ID or index in the ruleset you pass to it.
bool first = evaluator.Evaluate(record);
bool second = evaluator.Evaluate(record, "ID2");
bool third = evaluator.Evaluate(record, 2);
To evaluate all the rules of a ruleset in one step, as if they were one rule, use the overload that takes an EvaluationScope. With EvaluationScope.All it returns true only if every rule returns true, and with EvaluationScope.AtLeastOne if at least one does. The optional shortCircuit argument, true by default, tells the evaluator to stop as soon as the answer is known. Pass false to evaluate every rule, and invoke the setters and actions of each one that returns true, regardless of the overall outcome.
// True only if every rule of the ruleset returns true
bool all = evaluator.Evaluate(record, EvaluationScope.All);
// True if at least one does; evaluates the rest too and invokes their actions
bool any = evaluator.Evaluate(record, EvaluationScope.AtLeastOne, shortCircuit: false);
Evaluators
Code Effects employs two classes and multiple overloads of the extension Evaluate(..) and Filter(..) methods for rule evaluation and data filtering.
Evaluator and Evaluator<TSource> classes are designed to evaluate or filter large amounts of data against large rulesets or queries.
var evaluator = new Evaluator<SourceObjectType>(ruleXmlString);
var data = // get data for evaluation...
foreach(SourceObjectType record in data)
bool success = evaluator.Evaluate(record);
Extension Methods are designed for cases when you just need to evaluate a number of records against a single rule or a small ruleset.
bool success = sourceInstance.Evaluate(ruleXmlString);
An evaluator caches what it compiles, so create it once and reuse it for as long as the rules do not change. The non-generic Evaluator also has a constructor for a Flex Source, where the data is not a .NET object.
The Code Effects evaluation engine is an extremely fast business rules engine: in our tests, the generic Evaluator<T> evaluates a million objects against a simple rule in about a tenth of a second on a single thread; see Evaluation Performance Tips for the figures and what affects them. Because the business needs of organizations and industries can have unforeseeable differences, Code Effects engine attempts to be as forgiving as possible, allowing developers to use many kinds of scenarios, and throwing exceptions only when the result of rule evaluation is clearly unpredictable. For example, it allows comparisons of different .NET numeric types without asking developers for explicit boxing or type conversion. It also provides internal type conversion between nullable and regular types when preparing the source for evaluation. An exception carries a control number, such as GH7427, that says what is wrong.
The engine does not guess at Rule XML it cannot read. Since version 7, an evaluator refuses a document that contains an element it does not know, with control number GH7417, when it is created, instead of skipping the element and returning a result anyway. A typing error in hand-edited XML, or a rule written by a newer version of Code Effects, is therefore found when the rule is loaded, not after it has made decisions.
Evaluation Parameters
The EvaluationParameters class, which you pass to the constructor of an evaluator, has more properties than the ones above:
RuleResolver and TypeResolver find the Rule XML of the rules that a rule calls, and the types that the rules name by their alias.
Tracer takes a function that the engine calls as it evaluates, for debugging and logging.
PerformNullChecks is true by default and makes the engine add safety checks to the compiled rule, so that a null in the path to a value does not throw an exception.
MaxIterations limits the number of iterations of a rule in the Loop mode before the evaluation fails. The default, -1, sets no limit.
Precision rounds decimal and double values to the number of fractional digits you give before they are compared, and MidpointRounding sets the rounding algorithm. The default is no rounding, and round-to-even.
AssemblyWhitelist restricts the assemblies that the engine may load types from and invoke methods on; see Assembly Whitelisting.
Recording Evaluations with Audit
An application that loads its rules from the Rule Repository can record every evaluation with Audit. Load the rules through the application's AuditRecorder and attach it to the evaluation parameters; the rules are then evaluated exactly as before, and each evaluation is recorded: the rule and source versions, the values the engine read, the branch it took and what it set. Recording happens in the background and costs microseconds per evaluation. In the Rule Repository, any recorded decision can then be replayed step by step and explained.
using CodeEffects.Rule.Audit;
using CodeEffects.Rule.Common.Models;
using CodeEffects.Rule.Engine;
AuditRuleset rules = audit.GetRules(RuleQuery.BySource("Acme.Orders.Order"));
var parameters = new EvaluationParameters();
audit.Attach(parameters);
var evaluator = new Evaluator<Order>(rules.Xml, parameters);
bool approved = evaluator.Evaluate(order, rules.Rule("Approve large orders").Id);
See Recording Evaluations for the complete setup.
See also Evaluation Performance Tips.