Java IoT Authors: Pat Romanski, Elizabeth White, Charlotte Spencer-Smith, David Sprott, Liz McMillan

Related Topics: Java IoT

Java IoT: 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:


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:


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

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

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
    Cognitive Computing is becoming the foundation for a new generation of solutions that have the potential to transform business. Unlike traditional approaches to building solutions, a cognitive computing approach allows the data to help determine the way applications are designed. This contrasts with conventional software development that begins with defining logic based on the current way a business operates. In her session at 18th Cloud Expo, Judith S. Hurwitz, President and CEO of Hurwitz & ...
    SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 ad...
    SYS-CON Events announced today that Alert Logic, Inc., the leading provider of Security-as-a-Service solutions for the cloud, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Alert Logic, Inc., provides Security-as-a-Service for on-premises, cloud, and hybrid infrastructures, delivering deep security insight and continuous protection for customers at a lower cost than traditional security solutions. Ful...
    The Quantified Economy represents the total global addressable market (TAM) for IoT that, according to a recent IDC report, will grow to an unprecedented $1.3 trillion by 2019. With this the third wave of the Internet-global proliferation of connected devices, appliances and sensors is poised to take off in 2016. In his session at @ThingsExpo, David McLauchlan, CEO and co-founder of Buddy Platform, will discuss how the ability to access and analyze the massive volume of streaming data from mil...
    Join us at Cloud Expo | @ThingsExpo 2016 – June 7-9 at the Javits Center in New York City and November 1-3 at the Santa Clara Convention Center in Santa Clara, CA – and deliver your unique message in a way that is striking and unforgettable by taking advantage of SYS-CON's unmatched high-impact, result-driven event / media packages.
    SYS-CON Events announced today that Commvault, a global leader in enterprise data protection and information management, has been named “Bronze Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Commvault is a leading provider of data protection and information management...
    With an estimated 50 billion devices connected to the Internet by 2020, several industries will begin to expand their capabilities for retaining end point data at the edge to better utilize the range of data types and sheer volume of M2M data generated by the Internet of Things. In his session at @ThingsExpo, Don DeLoach, CEO and President of Infobright, will discuss the infrastructures businesses will need to implement to handle this explosion of data by providing specific use cases for filte...
    WebSocket is effectively a persistent and fat pipe that is compatible with a standard web infrastructure; a "TCP for the Web." If you think of WebSocket in this light, there are other more hugely interesting applications of WebSocket than just simply sending data to a browser. In his session at 18th Cloud Expo, Frank Greco, Director of Technology for Kaazing Corporation, will compare other modern web connectivity methods such as HTTP/2, HTTP Streaming, Server-Sent Events and new W3C event APIs ...
    SYS-CON Events announced today that Pythian, a global IT services company specializing in helping companies adopt disruptive technologies to optimize revenue-generating systems, has been named “Bronze Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Founded in 1997, Pythian is a global IT services company that helps companies compete by adopting disruptive technologies such as cloud, Big Data, advanced analytics, and DevO...
    SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Avere delivers a more modern architectural approach to storage that doesn’t require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbuilding of data centers ...
    Fortunately, meaningful and tangible business cases for IoT are plentiful in a broad array of industries and vertical markets. These range from simple warranty cost reduction for capital intensive assets, to minimizing downtime for vital business tools, to creating feedback loops improving product design, to improving and enhancing enterprise customer experiences. All of these business cases, which will be briefly explored in this session, hinge on cost effectively extracting relevant data from ...
    Companies can harness IoT and predictive analytics to sustain business continuity; predict and manage site performance during emergencies; minimize expensive reactive maintenance; and forecast equipment and maintenance budgets and expenditures. Providing cost-effective, uninterrupted service is challenging, particularly for organizations with geographically dispersed operations.
    With the Apple Watch making its way onto wrists all over the world, it’s only a matter of time before it becomes a staple in the workplace. In fact, Forrester reported that 68 percent of technology and business decision-makers characterize wearables as a top priority for 2015. Recognizing their business value early on, FinancialForce.com was the first to bring ERP to wearables, helping streamline communication across front and back office functions. In his session at @ThingsExpo, Kevin Roberts...
    As enterprises work to take advantage of Big Data technologies, they frequently become distracted by product-level decisions. In most new Big Data builds this approach is completely counter-productive: it presupposes tools that may not be a fit for development teams, forces IT to take on the burden of evaluating and maintaining unfamiliar technology, and represents a major up-front expense. In his session at @BigDataExpo at @ThingsExpo, Andrew Warfield, CTO and Co-Founder of Coho Data, will dis...
    SYS-CON Events announced today that iDevices®, the preeminent brand in the connected home industry, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. iDevices, the preeminent brand in the connected home industry, has a growing line of HomeKit-enabled products available at the largest retailers worldwide. Through the “Designed with iDevices” co-development program and its custom-built IoT Cloud Infrastruc...
    Eighty percent of a data scientist’s time is spent gathering and cleaning up data, and 80% of all data is unstructured and almost never analyzed. Cognitive computing, in combination with Big Data, is changing the equation by creating data reservoirs and using natural language processing to enable analysis of unstructured data sources. This is impacting every aspect of the analytics profession from how data is mined (and by whom) to how it is delivered. This is not some futuristic vision: it's ha...
    Silver Spring Networks, Inc. (NYSE: SSNI) extended its Internet of Things technology platform with performance enhancements to Gen5 – its fifth generation critical infrastructure networking platform. Already delivering nearly 23 million devices on five continents as one of the leading networking providers in the market, Silver Spring announced it is doubling the maximum speed of its Gen5 network to up to 2.4 Mbps, increasing computational performance by 10x, supporting simultaneous mesh communic...
    The cloud promises new levels of agility and cost-savings for Big Data, data warehousing and analytics. But it’s challenging to understand all the options – from IaaS and PaaS to newer services like HaaS (Hadoop as a Service) and BDaaS (Big Data as a Service). In her session at @BigDataExpo at @ThingsExpo, Hannah Smalltree, a director at Cazena, will provide an educational overview of emerging “as-a-service” options for Big Data in the cloud. This is critical background for IT and data profes...
    SYS-CON Events announced today that Men & Mice, the leading global provider of DNS, DHCP and IP address management overlay solutions, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. The Men & Mice Suite overlay solution is already known for its powerful application in heterogeneous operating environments, enabling enterprises to scale without fuss. Building on a solid range of diverse platform support,...
    One of the bewildering things about DevOps is integrating the massive toolchain including the dozens of new tools that seem to crop up every year. Part of DevOps is Continuous Delivery and having a complex toolchain can add additional integration and setup to your developer environment. In his session at @DevOpsSummit at 18th Cloud Expo, Miko Matsumura, Chief Marketing Officer of Gradle Inc., will discuss which tools to use in a developer stack, how to provision the toolchain to minimize onboa...