Welcome!

Java Authors: Yeshim Deniz, Pat Romanski, Jim Kaskade, Liz McMillan, Elizabeth White

Related Topics: Java

Java: Article

Does Your Project Need a Rule Engine

Separating the business rules from the application logic

Many Java developers today have moved toward some form of logging and/or unit test framework, and their code has been purged of many System.out. println() statements that were the traditional approach. Now perhaps it's time to get rid of some of those if ( x ) {. . .} as well. Nothing in a piece of code seems to foul up the design as much as the business logic, and going from two-tier to three-tier to n-tier hasn't done much to solve that problem.

In some dark layer of the code there is still a tangled mass of ifs, elses, and look-up tables upon which the whole thing rests. After a project goes through a few generations of developers, the "business rule" layer becomes a Gordian knot that defies both change and comprehension. Rule engines offer a framework for isolating the business logic in your applications; this framework is simpler and more flexible than look-up tables. As a design approach, it fits Java programs of almost every conceivable form, purpose, and budget. Most important, it brings the elusive goal of code reuse a step closer. This article lays the foundation for getting started using a rule engine on your own project.

What Is a Rule Engine?
A rule engine is a system for applying some set of if/then rules to the data in a system and then taking some action on the data or the system itself. Its primary purpose is to separate the business logic from the system logic - to externalize the business logic so it can be maintained separately. Use a rule engine to separate the if/then rules from system code - to externalize them so they can be maintained separately from the system code. The behavior of the system can then be modified without changing code or needing to recompile/redeploy. Rules are stored in human-readable form in a file so they can be changed with a text editor or rule editor.

For example, a typical storefront system might involve code to calculate a discount:


if (product.quantity > 100) {
	product.discount = 2;
} else if (product.quantity >= 500 && product.quantity < 2000) {
	product.discount = 5;
} else if (product.quantity >= 2000) {
	product.discount = 10;
}

A rule engine replaces the above with code that looks like this:

ruleEngine.applyRules(product);

The code no longer contains any reference to quantity or discounts. That logic is being handled entirely by the rule engine. This example is something of a straw man since this kind of rule is usually handled with name-value pairs in a database. However, it illustrates the main goal of separating system behavior from system code.

Do You Need a Rule Engine?
Rule engines have traditionally been used in financial applications for such things as credit scoring and underwriting because of the many and complex business rules these applications require. Coding such rules directly into the application makes application maintenance difficult and expensive because they change so often. It also makes even the initial release of the application difficult because such rules are often changed between the time the code is written and the time it's deployed. So rule engines were devised to separate the business rules from the application logic.

However, virtually every application has some program logic that needs to change often or needs to change in ways not anticipated in the original design. The real question then is not do you need a rule engine but how much time and money will the rule engine save you? Even if you have only a small collection of rules that are subject to change, your project can benefit greatly by separating them from the rest of the program logic. This is particularly true during user acceptance testing when missed requirements and incorrect assumptions become evident. A rule engine enables you to make dramatic changes in system behavior without dramatic changes in your code, and it enables you to make changes at runtime.

A rule engine is also easier to use and integrate than a database table. If your code employs if/then logic based on look-up tables, it can be greatly simplified with a rule engine.

Why is a rule engine better than name-value pairs in a database? Name-value pairs are a tried and true way of handling business rules in a system. If we have a system that needs to compute a product discount on the basis of quantity purchased, we might create a table in a database that stores percent discounts by quantity (see Table 1).

In our code we would construct a layer to manage querying this table with something like select discount from discount_tbl where quantity = 100. Then in the code that handles business logic, we would plug in a variable to handle the value returned by this query. If the discount ever changes, we simply modify the contents of the table. This works fine until the time comes when we want to stop using quantity to calculate discount and use some metric for customer buying patterns instead. What if we only want to do this for a single product for a few days? Basically we can't. We would have to recode the system to query by buying pattern, add new tables to the database to store the pairs, and create new program logic. Then we would have to undo it all a few days later.

Why does this well-used design turn out to be so inflexible? Because most of the rule is still coded into the system. Both the attribute being checked as well as the action being taken - the behavior of the system - are hard-coded. We have flexibility only in the degree to which something is done, not in what is being done.

By contrast, a rule engine provides the flexibility to change not only how much, but what, when, where, or any other basis you can imagine. There is no query, no table, and no rule-specific code. There is only a call to the rule engine passing raw data and getting back processed data. All of the logic of what to change as well as the basis for that change is controlled by the rule engine. Before, we were limited to the tweaking of values; now we can change the way the system lets us do business.

The Basic Flow
How does a rule engine fit into the flow of an application? Basically, it's just another class that you instantiate or to which you get a remote reference. Data goes in, rules are executed, and data comes out. You can also write rules that perform some action on the system based on the data you pass it. When the data is passed in, the rule engine interrogates the object to see which conditions in your rules are satisfied. If, for example, you have a rule:

If quantity > 100 Then do something

the rule engine will call the getQuan-tity() method on the object being passed in and compare the return from that call to the value "100." Then it will do something depending on whether the comparison is true or false.

A rule engine sits in your application in exactly the same way as a specialized class written to handle business rules.

Rule Engine Integration
Most of the rule engines available today loosely implement the JSR 94 specification, providing some commonality to integrating engines from different vendors. Thanks to JSR 94, integrating a rule engine into an application requires very few lines of code. It can be summed up in these few general steps:

  • Obtain an instance of the RuleRuntime object.
  • Get a RuleSession object from the RuleRuntime.
  • Pass data to the rule session object.
  • Execute the rules.
In a typical application, the first two steps occur once. Getting RuleSessions, passing data, and executing rules happen as many times as needed.

Listing 1 shows how it happens in the code for a typical Web-based insurance application using the rules4J rule engine.

That's really all there is to it. Lines 3, 8, 13, and 15 in Listing 1 carry out each of the four general steps outlined above.

Line 4 obtains an instance of the Ruleruntime object. The two parameters passed here identify the path and name of the XML file that describes this particular rule server.

Line 9 gets a RuleSession object from the Ruleruntime. A rule session handles the execution of a single ruleset. The name of the ruleset in this example is seen in the line that sets the string m_currentRuleSetName:

TestServer:Test:EligibilityRuleset

The three components of this name are servername : rulebase : ruleset.

Line 14 adds a List of objects to the RuleSession. The basic operation of the RuleSession is to fire the ruleset once for each object in this List and apply the rules separately to each object. In our example, we put only one object into the List, but there is no limit.

Line 16 instructs the RuleSession to execute the rules. The call to getObjects() on line 17 is not really needed because the RuleSession is not a remote object and it is acting on references to the objects loaded into it. The JSR 94 specification actually calls for StatefulRuleSession.executeRules() to return a void. Only StatelessRuleSession.executeRules() returns a List.

A Real-World Example
This real-world example comes from an installer program I am currently working on. It creates a custom build and install of a system into a J2EE container. The motivation to use a rule engine for this problem is that the behavior of the installer can vary considerably depending on the OS, container, port assignments, and paths a user selects for the installation. This behavior has the potential to change frequently either because container specifics change from version to version or there's some new system configuration we want the installer to handle. It also seems a waste to write a new and different installer program for the demo, eval, and production versions of the system being installed. Instead, we would like to have one general purpose installer and be able to control the behavior through rules.

What do we put into the rule engine and what do we leave in the program? A general rule of thumb is to put system capability into your code and system behavior into your rules. For example, the code will have the capability to compile a Java file and create a JAR file with it, but the rules will describe the behavior that causes it to happen. The rules dictate which files get compiled and placed into a JAR, and the code does the actual JARing and compiling. If there is logic that's specific to the mechanics of compiling or creating a JAR file, it should probably stay in the code.

This rule of thumb helps to shape the purpose of each of the classes the installer will need. The classes for the installer application are shown in Figure 1.

  • Installer: Handles presentation of the GUI.
  • OSCommand: Handles the many OS commands the installer will need to be able to manage (e.g., copying files, creating directories, JARing files, compiling, etc.). It contains all the logic that pertains to the mechanics (or capability) of the application.
  • InstallParams: Models data collected from the user - container type, install locations, port assignment, etc.
  • InstallProcess: Drives the actual install process (taking input from the InstallParams class) and invokes the rule engine. It encapsulates the behavior of the application.
We are really interested in what happens inside the install() method of the InstallProcess class. This method is where we find the main logic that must sort through the user inputs and decide how to configure and install the system on the user's machine. User input is stored in the params object and passed from the Installer class. Listing 2 shows the logic as it might have been written in plain Java. (Listings 2-4 can be downloaded from www.sys-con.com/java/sourcec.cfm.)

Clearly, such code will need to be changed often as we add capability and respond to vendor changes. In Listing 3 we've taken all this logic and expressed it in an XML file. Different rule engines implement the expression of rules in very different ways, and JSR 94 has nothing to say about how the rules are implemented. Some vendors do this with XML and some have developed specialized rule languages to handle the task (e.g., Fair Isaac's Blaze). The XML file in Listing 3 follows the implementation for the rules4J rule engine.

With the rules now expressed in an external XML file, the install() method can be rewritten to invoke the rule engine. Since we initialize the Ruleserver in a constructor, the code in the install() method is reduced to just a few lines (see Listing 4).

The installer has been improved in two important ways:

1.  The install method is now very general and, in fact, the InstallProcess class has become reusable. Because the rule engine doesn't care what kind of object is being passed to it, we no longer need to write the install() method to take an instance of any particular class. This leaves us free to pass all manner of classes that contain user input. The only stipulation is that the rules we write in the rule engine match the properties in the parameter class.

2.  Almost anyone can read, understand, and modify the behavior of the class, and they can do so without needing to recompile the code. This is a tremendous advantage to test teams, customer support, and even the developers who must maintain it.

A Look at the Rule Engines Out There
There are a great many rule engines to choose from. Below is a sampling of the products out there.

ILOG JRules and Fair Isaac Blaze
JRules and Blaze have been the main players in the business rules rule engine market for some years. They have a well-established user base in the banking and insurance industries. These products are particularly well suited to enterprise applications because they offer a variety of tools for nonprogrammers and administrators. The only drawbacks to either of them are the price and the learning curve. If you are building a main-line business application in the financial services or insurance sectors, they are the obvious choice. www.ilog.com/products/jrules and www.blazesoft.com

WebLogic Personalization Server
BEA has taken the lead in developing JSR-94. Oddly enough, unless you're heavily plugged into the BEA line of products, you may not even realize that it offers a rule engine. In fact, it seems that many on the BEA sales team don't realize it either. I once sat in on a sales demo of WebLogic Portal and Personalization Server and never heard a word about it. Nonetheless, BEA does bundle a rule engine with its Portal product. http://e-docs.bea.com/wlcs/docs20/p13ndev

Rules4J and Java Expert System Shell (Jess)
These products are the emergent players in the field. They are easy to use and inexpensive but sacrifice nothing in basic capability to the bigger players. They are a good fit for most solutions, especially for small projects. They have a short learning curve. www.rules4j.com and http://herzberg.ca.sandia.gov/jess

Struts
Didn't expect to see this one here did you? Struts is not a rule engine, but it does have a set of <logic> tags that enable it to evaluate variables and control what is displayed on a JSP page. I've included it in the list only because I've been asked how it compares with rule engines on numerous occasions. If you're building a Web application with Struts, be sure to look at this capability. http://jakarta.apache.org/struts

Conclusion
Rule engines have been around for a long time. Charles Forgy designed the Rete (Latin for net) algorithm employed by most implementations back in 1982. Unfortunately, price and lack of uniformity have kept them out of the hands of developers on most projects. This has changed of late. Inexpensive, powerful, standards-based rule engines are available for projects of almost any budget - a good turn of events for systems engineering. The separation of system behavior from system capability is a key requirement for code reusability. The failure to separate behavior and capability has an inestimable cost, especially if Java's 2.5 million developers fail at it consistently. Hard-coding behavior certainly keeps us busy, but is it really a productive practice?

Related Reading

  • JSR 94 Specification: www.jcp.org/en/jsr/detail?id=094
  • Some good explanations of the Rete algorithm: http://herzberg.ca.sandia.gov/jess/docs/52/rete.html and www.cis.temple.edu/~ingargio/cis587/readings/rete.html
  • More Stories By Chris Moran

    Chris Moran is a senior Java developer and the chief architect of rules4J. He lives and works in the Washington, DC, area.

    Comments (6) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    Most Recent Comments
    James Taylor 06/27/06 11:11:03 AM EDT

    Nice article. Have you thought about writing something about how to engage business users in collaboration around business rules? The use of templates or other control mechanisms for instance? My blog has my thoughts on this and other topics.

    Chris Moran 11/07/04 06:15:42 PM EST

    Kevin raises a good point. There is a tendency to slip into proceduralism when designing rule-based applications. This is more a habit of thought than a consequence of using rule engines. I would only offer this advice: the rulebase should be structured and the rule engine used so that it simplifies coding of the classes but still reflects the class hierarchy and the application architecture. The ruleset hierarchy should reflect the class hierarchy. And if you design a service-oriented architecture, you should still have a service-oriented architecture after you incorporate a rule engine. Otherwise, you need to rethink your design of the rulesets and also the rules you think you need.

    Kevin 11/06/04 12:45:49 PM EST

    Good read...Excellent article - perhaps. I'm trying to figure out where this technology fits in. Can anyone tell me how a rules engine architecture fits in to say a service oriented architecture? Seems to me in a rules engine world the overall service architecture is so buggered up you can't tell what you have anymore - your "services" have all been abstracted into a single rules engine, database records and low level atomic classes which are now locked into a rules super class or interface. In the rules engine architecture you've lost your object hierarchy in favor of a flat list of atomic action classes - no structure. It may be I'm missing the forest for the trees. Perhaps rules engine archtectures should be applied very sparingly and targeted for higly changing computational oriented applications period. I see know way to reaonably re-use ANY part of the rules engines architecture in any other non-rules based architecure - this seems a very dangerous thing. Tell me where I'm going wrong.

    Prafull 06/14/04 12:58:35 AM EDT

    An excellent article.

    Chris Moran 06/05/04 10:31:16 AM EDT

    I recently did some testing with Aion. It does have a number of good features. Integration with it is not as clean because it is not a Java rule engine. It also does not implement JSR-94 in its API.

    Marcel 06/04/04 03:42:56 AM EDT

    Have you ever seen CA''s CleverPath Aion? Has been around for years. Multi Platform and used by many large corporateions.