Welcome!

Java Authors: Trevor Parsons, Rex Morrow, Datical, Elizabeth White, Peter Silva, Hovhannes Avoyan

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.

    @ThingsExpo Stories
    Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
    There will be 50 billion Internet connected devices by 2020. Today, every manufacturer has a propriety protocol and an app. How do we securely integrate these "things" into our lives and businesses in a way that we can easily control and manage? Even better, how do we integrate these "things" so that they control and manage each other so our lives become more convenient or our businesses become more profitable and/or safe? We have heard that the best interface is no interface. In his session at Internet of @ThingsExpo, Chris Matthieu, Co-Founder & CTO at Octoblu, Inc., will discuss how these devices generate enough data to learn our behaviors and simplify/improve our lives. What if we could connect everything to everything? I'm not only talking about connecting things to things but also systems, cloud services, and people. Add in a little machine learning and artificial intelligence and now we have something interesting...
    Last week, while in San Francisco, I used the Uber app and service four times. All four experiences were great, although one of the drivers stopped for 30 seconds and then left as I was walking up to the car. He must have realized I was a blogger. None the less, the next car was just a minute away and I suffered no pain. In this article, my colleague, Ved Sen, Global Head, Advisory Services Social, Mobile and Sensors at Cognizant shares his experiences and insights.
    We are reaching the end of the beginning with WebRTC and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) irreversibly encoded. In his session at Internet of @ThingsExpo, Peter Dunkley, Technical Director at Acision, will look at how this identity problem can be solved and discuss ways to use existing web identities for real-time communication.
    Can call centers hang up the phones for good? Intuitive Solutions did. WebRTC enabled this contact center provider to eliminate antiquated telephony and desktop phone infrastructure with a pure web-based solution, allowing them to expand beyond brick-and-mortar confines to a home-based agent model. It also ensured scalability and better service for customers, including MUY! Companies, one of the country's largest franchise restaurant companies with 232 Pizza Hut locations. This is one example of WebRTC adoption today, but the potential is limitless when powered by IoT. Attendees will learn real-world benefits of WebRTC and explore future possibilities, as WebRTC and IoT intersect to improve customer service.
    From telemedicine to smart cars, digital homes and industrial monitoring, the explosive growth of IoT has created exciting new business opportunities for real time calls and messaging. In his session at Internet of @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, will share some of the new revenue sources that IoT created for Restcomm – the open source telephony platform from Telestax. Ivelin Ivanov is a technology entrepreneur who founded Mobicents, an Open Source VoIP Platform, to help create, deploy, and manage applications integrating voice, video and data. He is the co-founder of TeleStax, an Open Source Cloud Communications company that helps the shift from legacy IN/SS7 telco networks to IP-based cloud comms. An early investor in multiple start-ups, he still finds time to code for his companies and contribute to open source projects.
    The Internet of Things (IoT) promises to create new business models as significant as those that were inspired by the Internet and the smartphone 20 and 10 years ago. What business, social and practical implications will this phenomenon bring? That's the subject of "Monetizing the Internet of Things: Perspectives from the Front Lines," an e-book released today and available free of charge from Aria Systems, the leading innovator in recurring revenue management.
    The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges.
    There’s Big Data, then there’s really Big Data from the Internet of Things. IoT is evolving to include many data possibilities like new types of event, log and network data. The volumes are enormous, generating tens of billions of logs per day, which raise data challenges. Early IoT deployments are relying heavily on both the cloud and managed service providers to navigate these challenges. In her session at 6th Big Data Expo®, Hannah Smalltree, Director at Treasure Data, to discuss how IoT, Big Data and deployments are processing massive data volumes from wearables, utilities and other machines.
    All major researchers estimate there will be tens of billions devices – computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be!
    P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Erik Lagerway, Co-founder of Hookflash, will walk through the shifting landscape of traditional telephone and voice services to the modern P2P RTC era of OTT cloud assisted services.
    While great strides have been made relative to the video aspects of remote collaboration, audio technology has basically stagnated. Typically all audio is mixed to a single monaural stream and emanates from a single point, such as a speakerphone or a speaker associated with a video monitor. This leads to confusion and lack of understanding among participants especially regarding who is actually speaking. Spatial teleconferencing introduces the concept of acoustic spatial separation between conference participants in three dimensional space. This has been shown to significantly improve comprehension and conference efficiency.
    The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, will discuss single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example to explain some of these concepts including when to use different storage models.
    SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridstore delivers vmOptimized™ Storage that self-optimizes to each application or VM across both virtual and physical environments. Leveraging a grid architecture, Gridstore delivers the first end-to-end storage QoS to ensure the most important App or VM performance is never compromised. The storage grid, that uses Gridstore’s performance optimized nodes or capacity optimized nodes, starts with as few a...
    The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace. These technological reforms have not only changed computers and smartphones, but are also changing the data processing model for all information devices. In particular, in the area known as M2M (Machine-To-Machine), there are great expectations that information with a new type of value can be produced using a variety of devices and sensors saving/sharing data via the network and through large-scale cloud-type data processing. This consortium believes that attaching a huge number of devic...
    Innodisk is a service-driven provider of industrial embedded flash and DRAM storage products and technologies, with a focus on the enterprise, industrial, aerospace, and defense industries. Innodisk is dedicated to serving their customers and business partners. Quality is vitally important when it comes to industrial embedded flash and DRAM storage products. That’s why Innodisk manufactures all of their products in their own purpose-built memory production facility. In fact, they designed and built their production center to maximize manufacturing efficiency and guarantee the highest quality of our products.
    Can call centers hang up the phones for good? Intuitive Solutions did. WebRTC enabled this contact center provider to eliminate antiquated telephony and desktop phone infrastructure with a pure web-based solution, allowing them to expand beyond brick-and-mortar confines to a home-based agent model. Download Slide Deck: ▸ Here
    All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. Over the summer Gartner released its much anticipated annual Hype Cycle report and the big news is that Internet of Things has now replaced Big Data as the most hyped technology. Indeed, we're hearing more and more about this fascinating new technological paradigm. Every other IT news item seems to be about IoT and its implications on the future of digital business.
    BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
    With the iCloud scandal seemingly in its past, Apple announced new iPhones, updates to iPad and MacBook as well as news on OSX Yosemite. Although consumers will have to wait to get their hands on some of that new stuff, what they can get is the latest release of iOS 8 that Apple made available for most in-market iPhones and iPads. Originally announced at WWDC (Apple’s annual developers conference) in June, iOS 8 seems to spearhead Apple’s newfound focus upon greater integration of their products into everyday tasks, cross-platform mobility and self-monitoring. Before you update your device, here is a look at some of the new features and things you may want to consider from a mobile security perspective.