Click here to close now.


Java IoT Authors: Pat Romanski, Liz McMillan, Chris Fleck, Gary Kaiser, Elizabeth White

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) { = 2;
} else if (product.quantity >= 500 && product.quantity < 2000) { = 5;
} else if (product.quantity >= 2000) { = 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

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. and

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.

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. and

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.

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:
  • Some good explanations of the Rete algorithm: and
  • 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
    Nowadays, a large number of sensors and devices are connected to the network. Leading-edge IoT technologies integrate various types of sensor data to create a new value for several business decision scenarios. The transparent cloud is a model of a new IoT emergence service platform. Many service providers store and access various types of sensor data in order to create and find out new business values by integrating such data.
    There are so many tools and techniques for data analytics that even for a data scientist the choices, possible systems, and even the types of data can be daunting. In his session at @ThingsExpo, Chris Harrold, Global CTO for Big Data Solutions for EMC Corporation, will show how to perform a simple, but meaningful analysis of social sentiment data using freely available tools that take only minutes to download and install. Participants will get the download information, scripts, and complete end-to-end walkthrough of the analysis from start to finish. Participants will also be given the pract...
    Too often with compelling new technologies market participants become overly enamored with that attractiveness of the technology and neglect underlying business drivers. This tendency, what some call the “newest shiny object syndrome,” is understandable given that virtually all of us are heavily engaged in technology. But it is also mistaken. Without concrete business cases driving its deployment, IoT, like many other technologies before it, will fade into obscurity.
    SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in high-performance, high-efficiency server, storage technology and green computing, will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/Big Data, HPC and Embedded Systems worldwide. Supermi...
    WebRTC services have already permeated corporate communications in the form of videoconferencing solutions. However, WebRTC has the potential of going beyond and catalyzing a new class of services providing more than calls with capabilities such as mass-scale real-time media broadcasting, enriched and augmented video, person-to-machine and machine-to-machine communications. In his session at @ThingsExpo, Luis Lopez, CEO of Kurento, will introduce the technologies required for implementing these ideas and some early experiments performed in the Kurento open source software community in areas ...
    Electric power utilities face relentless pressure on their financial performance, and reducing distribution grid losses is one of the last untapped opportunities to meet their business goals. Combining IoT-enabled sensors and cloud-based data analytics, utilities now are able to find, quantify and reduce losses faster – and with a smaller IT footprint. Solutions exist using Internet-enabled sensors deployed temporarily at strategic locations within the distribution grid to measure actual line loads.
    “In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
    The Internet of Everything is re-shaping technology trends–moving away from “request/response” architecture to an “always-on” Streaming Web where data is in constant motion and secure, reliable communication is an absolute necessity. As more and more THINGS go online, the challenges that developers will need to address will only increase exponentially. In his session at @ThingsExpo, Todd Greene, Founder & CEO of PubNub, will explore the current state of IoT connectivity and review key trends and technology requirements that will drive the Internet of Things from hype to reality.
    There will be 20 billion IoT devices connected to the Internet soon. What if we could control these devices with our voice, mind, or gestures? What if we could teach these devices how to talk to each other? What if these devices could learn how to interact with us (and each other) to make our lives better? What if Jarvis was real? How can I gain these super powers? In his session at 17th Cloud Expo, Chris Matthieu, co-founder and CTO of Octoblu, will show you!
    Today’s connected world is moving from devices towards things, what this means is that by using increasingly low cost sensors embedded in devices we can create many new use cases. These span across use cases in cities, vehicles, home, offices, factories, retail environments, worksites, health, logistics, and health. These use cases rely on ubiquitous connectivity and generate massive amounts of data at scale. These technologies enable new business opportunities, ways to optimize and automate, along with new ways to engage with users.
    Through WebRTC, audio and video communications are being embedded more easily than ever into applications, helping carriers, enterprises and independent software vendors deliver greater functionality to their end users. With today’s business world increasingly focused on outcomes, users’ growing calls for ease of use, and businesses craving smarter, tighter integration, what’s the next step in delivering a richer, more immersive experience? That richer, more fully integrated experience comes about through a Communications Platform as a Service which allows for messaging, screen sharing, video...
    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! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal an...
    SYS-CON Events announced today that Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, will keynote at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA.
    WebRTC converts the entire network into a ubiquitous communications cloud thereby connecting anytime, anywhere through any point. In his session at WebRTC Summit,, Mark Castleman, EIR at Bell Labs and Head of Future X Labs, will discuss how the transformational nature of communications is achieved through the democratizing force of WebRTC. WebRTC is doing for voice what HTML did for web content.
    As a company adopts a DevOps approach to software development, what are key things that both the Dev and Ops side of the business must keep in mind to ensure effective continuous delivery? In his session at DevOps Summit, Mark Hydar, Head of DevOps, Ericsson TV Platforms, will share best practices and provide helpful tips for Ops teams to adopt an open line of communication with the development side of the house to ensure success between the two sides.
    The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
    The IoT market is on track to hit $7.1 trillion in 2020. The reality is that only a handful of companies are ready for this massive demand. There are a lot of barriers, paint points, traps, and hidden roadblocks. How can we deal with these issues and challenges? The paradigm has changed. Old-style ad-hoc trial-and-error ways will certainly lead you to the dead end. What is mandatory is an overarching and adaptive approach to effectively handle the rapid changes and exponential growth.
    Today air travel is a minefield of delays, hassles and customer disappointment. Airlines struggle to revitalize the experience. GE and M2Mi will demonstrate practical examples of how IoT solutions are helping airlines bring back personalization, reduce trip time and improve reliability. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Dr. Sarah Cooper, M2Mi's VP Business Development and Engineering, will explore the IoT cloud-based platform technologies driving this change including privacy controls, data transparency and integration of real time context w...
    Developing software for the Internet of Things (IoT) comes with its own set of challenges. Security, privacy, and unified standards are a few key issues. In addition, each IoT product is comprised of at least three separate application components: the software embedded in the device, the backend big-data service, and the mobile application for the end user's controls. Each component is developed by a different team, using different technologies and practices, and deployed to a different stack/target - this makes the integration of these separate pipelines and the coordination of software upd...
    The IoT is upon us, but today’s databases, built on 30-year-old math, require multiple platforms to create a single solution. Data demands of the IoT require Big Data systems that can handle ingest, transactions and analytics concurrently adapting to varied situations as they occur, with speed at scale. In his session at @ThingsExpo, Chad Jones, chief strategy officer at Deep Information Sciences, will look differently at IoT data so enterprises can fully leverage their IoT potential. He’ll share tips on how to speed up business initiatives, harness Big Data and remain one step ahead by apply...