4.1 Externalizing Business Rules with NxBRE

Hard-coded business rules can lead to inflexible applications that are hard to maintain. NxBRE is an open source business rules engine that helps you build more agile systems by externalizing the processing of these rules.

NxBRE started as a C# conversion of Sloan Seaman’s JxBRE and has since been vastly extended. Mainly written by David Dossot, NxBRE is available on SourceForge, where it benefits from the functional and technical feedback of a vibrant community.

NxBRE offers two different engine flavors to better fit the skills and knowledge of developers: the Flow Engine suits the procedural-minded, while the Inference Engine is more oriented toward expert system connoisseurs. All rule files are expressed in XML, which allows for easy editing, validation, and transformation. The Inference Engine also supports rules written in a Prolog-like syntax and comes with a dedicated Stencil for Microsoft Visio 2003 that allows graphical editing of rule bases.

NxBRE at a Glance

Tool

NxBRE

Version covered

2.5.1

Home page

http://www.agilepartner.net/oss/nxbre/

Power Tools page

http://www.windevpowertools.com/tools/142

Summary

Software component for executing business rules expressed in XML. Usable in standalone or multithreaded systems.

License type

LGPL

Online resources

Documentation, online knowledge base (Wiki), forums

Supported Frameworks

.NET 1.1, 2.0

Getting Started

NxBRE is distributed for .NET 1.1 but can be recompiled on .NET 2.0. You can download the distribution from the tool’s SourceForge page (http://sourceforge.net/projects/nxbre/). NxBRE’s distribution contains the DLL built-in debug and release modes, which you can directly reference in your projects.

NUnit 2.2 (available from http://www.nunit.org) is required for running the test suite.

NxBRE has primarily been developed with the open source IDE SharpDevelop, but it is distributed with project files for Visual Studio .NET 2003 and XML build files for NAnt.

Tip

A command-line console is available for easily testing rule bases designed for the Inference Engine. It is distributed as an independent package in the same SourceForge project.

Using NxBRE

A business rule generally consists of a condition followed by one or several actions executed if the condition is met.

The following is a classical set of business rules for computing sales discount:

Rule #1

The discount for a customer buying a product is 5.0 percent if the customer is premium and the product is regular.

Rule #2

The discount for a customer buying a product is 7.5 percent if the customer is premium and the product is luxury.

Rule #3

A customer is premium if his spending has been min 5000 Euro in the previous year.

We’ll see how these rules translate to a rule base momentarily. A rule base is a file that contains the definitions of several business rules. NxBRE uses these rule bases to control its processing.

Creating rule bases for the Flow Engine

NxBRE does not provide any facility for editing rules for the Flow Engine. Since the rules expressed in XML are similar to traditional flow-control programming, using an XML editor such as jEdit (Figure 4-1) that supports schema validation and offers contextual element insertion is generally sufficient.

Using jEdit to create flow-control rules

Figure 4-1. Using jEdit to create flow-control rules

The example Rule #1 shown previously can be expressed this way:

<Logic>
    <If>
      <And>
          <Equals leftId="CLIENT_RATING" rightId="PREMIUM_RATING" />
          <Equals leftId="PRODUCT_TYPE" rightId="REGULAR_TYPE" />
      </And>
      <Do>
          <Integer id="DISCOUNT_PERCENT" value="5" />
      </Do>
    </If>
</Logic>

The Flow Engine contains an HTML-rendering engine that offers a convenient way to navigate through rules and read them transformed into pseudocode. Figure 4-2 shows one of NxBRE’s unit test rule files transformed in such a manner.

HTML pseudocode rendering of flow-control rules

Figure 4-2. HTML pseudocode rendering of flow-control rules

Tip

To organize big rule bases, it is a good idea to leverage the notion of a rule set that is supported by the Flow Engine. It allows you to group several rules into a named group that gets evaluated on demand.

Creating rules for the Inference Engine

NxBRE supports several rule formats for its Inference Engine:

  • RuleML files, an XML-based representation of rules

  • Microsoft Visio 2003 VDX files

  • HRF files, a human-readable format that resembles Prolog

Tip

RuleML is the format of choice of the Inference Engine. Not all the features are available in the other formats.

RuleML files can be directly authored with any schema-aware XML editor. The example Rule #1 shown previously can be expressed this way:

<Implies>
    <And>
        <Atom>
            <Rel>premium</Rel>
            <Var>customer</Var>
        </Atom>
        <Atom>
            <Rel>regular</Rel>
            <Var>product</Var>
        </Atom>
    </And>
    <Atom>
        <Rel>discount</Rel>
        <Var>customer</Var>
        <Var>product</Var>
        <Ind>5.0 percent</Ind>
    </Atom>
</Implies>

Tip

RuleML goes much further than simple if/then statements. In fact, NxBRE’s forward-chaining Inference Engine performs pattern-matching operations and can produce combinations of matching data. See http://ruleml.org and NxBRE’s user guide for more information.

Editing rules in Visio offers several advantages, including the possibility of organizing rules in pages (Figure 4-3) or mixing rule elements with other schema elements (Figure 4-4).

Designing Inference Engine rules with Visio

Figure 4-3. Designing Inference Engine rules with Visio

HRF can be authored with any text editor. Our example Rule #1 would be written like this in HRF:

( premium{?customer}
& regular{?product} )
-> discount{?customer, ?product, 5.0 percent};

Whatever rule format is chosen, NxBRE provides a testing console as a companion package. As shown in Figure 4-5, this console allows you to easily load, run, and trace the processing of rule bases designed for the Inference Engine.

Implementing the engine

Using NxBRE in a project typically involves the following steps:

  1. Instantiating the engine

  2. Loading a rule base

  3. Storing data in memory

  4. Running the engine

  5. Analyzing the results

Mixing rules and other schema elements

Figure 4-4. Mixing rules and other schema elements

Tip

It is not possible to programmatically define rules in NxBRE.

As shown in Figure 4-6, the memory where data is loaded is called context for the Flow Engine and is called working memory for the Inference Engine. Context and working memory contain references to object instances and bits of knowledge called facts, respectively.

The following code shows a typical usage of the Flow Engine:

IFlowEngine bre = new BREImpl( );
bre.Init(new XBusinessRulesFileDriver(ruleFile))
bre.RuleContext.SetObject("TestObject", tobj);
bre.Process( );
// check the modifications made on tobj
Testing a rule base with the Inference Engine Console

Figure 4-5. Testing a rule base with the Inference Engine Console

Architecture of NxBRE

Figure 4-6. Architecture of NxBRE

And the following code shows a typical usage of the Inference Engine:

IInferenceEngine ie = new IEImpl( );
ie.LoadRuleBase(new RuleML09NafDatalogAdapter(
    ruleFile, FileAccess.Read));
ie.Assert(new Fact("is the father of", new Individual("John Smith"),
    new Individual("Kyle Doe"));
ie.Process( );
// query the fact base for deduced facts

The Inference Engine can leverage a binder, which is a file that plays a role similar to ASP.NET code-behind files. The binder, which can be either an on-the-fly compiled C# class or a flow control rule file, is used to retrieve data from enterprise sources or business objects, to analyze complex expressions, and to perform data changes based on the engine deductions.

Tip

Using a binder contributes to a versatile implementation because it is dynamically evaluated and can therefore be altered at runtime.

The binder is also able to consume events raised by the engine when deductions are made: these events can be leveraged to implement reaction code that directly modifies business objects or enterprise data sources, instead of analyzing the memory of the engine after process time and mapping its state to the said objects and data sources.

While the Flow and Inference Engines are not thread-safe objects, NxBRE’s documentation details recommend implementation strategies for multithreaded environments such as ASP.NET or Enterprise Services.

Tip

A registry that facilitates the implementation of the Inference Engine in a multithreaded environment, with support for hot reloading of rule bases and binders, has recently been contributed as an extra package for NxBRE.

Getting Support

Support for NxBRE is available either through the online SourceForge forums or via email by writing to support@nxbre.org.

Get Windows Developer Power Tools now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.