Home > Java > Leveraging a Business Rule Engine

Leveraging a Business Rule Engine

JBoss Drools Expert (or JBoss Rules for the enterprise version of Drools supported by Red Hat) is a business rule engine.  You may have heard of a Rule Engine in the past but were unsure of how it can benefit you and your application.  In the following paragraphs, I will list some of the benefits of using a Rule Engine in a traditional web application, the different formats used to express rules in Drools, and a general overview of how Drools is used.

Benefits of using a Rule Engine:
Separates the Business Rule lifecyle from the Application lifecyle
In many applications, the business rules change more often than the application code.  Moving your rules to a Rule Engine allows them to be updated independently of the application source code.  This would allow rule changes to occur much more rapidly than the alternative of a full production release of the application.

Simplifies creating/modifying business rules
Instead of having nested “if..else” statements littered throughout your codebase, you have a known set of rule files.  Rules expressed in the Drools Rule Language (DRL), a Domain Specific Language, or a Decision Table are easier to understand because the format is clearer compared to nested “if..else” statements in the source code.  It is possible for business analysts to create and modify rules without needing a developer’s assistance depending on the tools available to the business analyst.

Fosters reuse and creates a central point of knowledge
The benefit of business rules being easier to modify/update is multiplied if you use the same rules in multiple applications.  The centralization of rules in a Rule Engine forms a central point of knowledge.  For example, if 5 applications use many of the same rules, then a single change is needed to update all 5 applications.  Contrast this with updating a different implementation of the rules in each of the 5 applications.  This approach to updating the rules is less prone to errors and is much quicker to complete.

Increases the accessibility of rules so they can be verified and audited by experts
When not using a Rule Engine, developers implement the rules expressed in a requirements document into source code.  This translation step can introduce errors.  Further, requirements documents can become outdated.  Externalizing rules allows them to be quickly retrieved and reviewed by the business experts.  The technical skill level required to review them is reduced if the rules are expressed in the form of a Decision Table or Domain Specific Language.

Rule Formats using Drools 5.2

Drools Rule Language
Here is an example rule written in the drools rule language.  The file extension is .drl

rule "10 dollars off any order over 100 with 10off100 code"
      $cart : Cart(coupon == "10off100",
              subTotal > 100,
              now >= "25-Nov-2011",
              now <= "28-Nov-2011" )

Each rule has a name.  There is a left hand side (when) and a RHS (then).  When the LHS matches what you inserted into working memory, the RHS is executed.  As you can see, the LHS is basically pattern matching on object types and on the value of their attributes.  You can capture a match and store it in a variable (shown here as $cart).  This variable can be used to restrict the later patterns in the LHS or used as needed in the RHS.

Decision Table
A decision table is a specially formatted spreadsheet that is translated by Drools into the drools rule language.  Expressing rules in this format makes it easier to see missed scenarios.  Below is an example of a drools decision table.
drools decision table
In this example, Drools creates a rule in the drools rule language behind the scenes for you for each row of the table starting from row 9.  The columns are either conditions of the rule (LHS) or the action to take (RHS) when there is a match.  The colors shown in the spreadsheet are cosmetic.

The orange cells of the spreadsheet represent the rule domain objects and their attributes used in the rules.  The lower cells in white area are the data values for those attributes.

The rule for Row 9 says “if there is a driver having an age 18 to 24 years old with 0 prior claims and is applying for comprehensive insurance then give the driver a 1% discount on their policy.

Instead of using the drools rule engine and the populated decision table, you could implement this table in Java using normal “if..else” statements.  Lets look at one such implementation.

if (age >= 18 && age <= 24 && priorClaims == 0) {
    if (type.equals("COMPREHENSIVE")) {
    else if (type.equals("FIRE_THEFT")) {
} else if (age >= 25 && age <= 30 && priorClaims == 1 
        && type.equals("COMPREHENSIVE")) {

The small rule table with 3 conditions is starting to look very busy when translated to Java “if..else” statements with only a few rows implemented.  Imagine if each rule had 10 conditions.  The decision table would still be readable, however the corresponding Java code would be menacing.

Implementing the rules in this manner would no doubt involve much copy and paste.   This may lead to shortcuts to reduce the amount of code by nesting some of the “if..else” statements.  It may work fine, but maintainability would suffer.  What would happen if a condition changed and required some of the nesting to be eliminated?  For example, imagine a new rule was added for 18-24 wanting comprehensive with 1 prior claim.  There would be a ripple effect. Imagine if an a new condition needed to be added to the rules.  Using a decision table, this would be an extra column with the associated values.  Changing Java “if..else” statements would be a nightmare.

Domain Specific Language (DSL)
Another means available in Drools for expressing rules in a format friendly to non-technical users is to use a DSL.  A DSL empowers business experts to write rules using a set of phrases you developed collaboratively with them.  This enables them to express the rules in the language natural to their business domain in the form of a sentence.  Instead of cryptic code, it looks like a requirements document.  Here is an example DSL and rules written using it.

expander jpetstore.dsl
rule "10off50 coupon between nov 23 to 29 2011"
A customer prepares to place an order
- using coupon code "10off50"
- totaling at least 50 dollars
- starting on "23-Nov-2011"
- ending on "29-Nov-2011"
discount the order total by 10 dollars

DSL rule (jpetstore.dslr)

This format is easy to understand and allows the creation of multiple rules of this type quickly using GUI tools.  Further, not all of the restrictions on the order are required.  For example, the line specifying the coupon code could be eliminated which would then allow any order over $50 to obtain the $10 discount.

Now lets take a look at the technical side, the DSL definition, which would be created by a developer.

[when]A customer prepares to place an order=cart:Cart(subTotal > 0)
[when]- using coupon code "{coupon}"=coupon == "{coupon}"
[when]- totaling at least {value} dollars=subTotal >= {value}
[when]- starting on "{start}"=now >= "{start}"
[when]- ending on "{end}"=now <= "{end}"
[then]discount the order total by {amount} dollars=cart.setDiscount({amount});

DSL definition (jpetstore.dsl)

Basically, the phrase on the left is converted to the code on the right with the appropriate values used in the placeholders. Using the Drools IDE in Eclipse, you can see how rules written using a DSL (the .dslr file) are transformed into the drools rule language by clicking on the DRL viewer table in the Eclipse editor. 

Besides an increase in readability, you also gain an increase in flexibility when you use a DSL because the phrases are independent of the domain model.  You can change the domain model without impacting the rules that are written in the DSL.  Similarly, you can change the wording of the phrases independently of the domain model.  All that is required is a modification to the DSL definition.

General steps needed to use Drools in your application
Here is an overview of how to use Drools in your application:

  • Create a POJO (Plain Old Java Object) domain model complete with attributes. It should model all the concepts needed by your rules
  • Author your rules using your domain model in your desired format. The rules be written in the drools rule language, a decision table, or a domain specific language
  • Build a KnowledgeBase using one or more rule resources.
  • Create a KnowledgeSession from the KnowledgeBase
  • Insert populated POJOs into the KnowledgeSession
  • Run the rules which then modify the appropriate POJOs
  • Use the modified POJOs in your application

I’ve covered the benefits of using a Rule Engine, the different formats rules can be expressed using the Drools Rule Engine, and a general overview of the steps required to use Drools in your application.  In a later post, I will show how a shoppingcart can leverage a rules engine to implement some of the features we commonly see offered by online retailers.

To learn more about Drools and related products like Guvnor, you can visit the community project’s homepage. JBoss Rules, the enterprise version of Drools supported by Red Hat, also has its documentation available online.

Categories: Java Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: