Drools JBoss Rules 5.0 Developer's Guide

By Michal Bali
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

Business rules can help your business by providing a level of agility and flexibility. As a developer, you will be largely responsible for implementing these business rules effectively, but implementing them systematically can often be difficult due to their complexity. Drools, or JBoss Rules, makes the process of implementing these rules quicker and handles the complexity, making your life a lot easier!

This book guides you through all of the features of Drools, such as dynamic rules, the event model, and Rete implementation with high performance indexing. It will help you to set up the JBoss Rules platform and start creating your own business. It's easy to start developing with Drools if you follow its real-world examples that are intended to make your life easier.

Starting with an introduction to the basic syntax that is essential for writing rules, the book will guide you through validation and human-readable rules that define, maintain, and support your business agility. As a developer, you will be expected to represent policies, procedures and. constraints regarding how an enterprise conducts its business; this book makes it easier by showing you it can be done.

A real-life example of a banking domain allows you to see how the internal workings of the rules engine operate. A loan approval process example shows the use of the Drools Flow module. Parts of a banking fraud detection system are implemented with Drools Fusion module, which is the Complex Event Processing part of Drools. This in turn, will help developers to work on preventing fraudulent users from accessing systems in an illegal way.

Finally, more technical details are shown on the inner workings of Drools, the implementation of the ReteOO algorithm, indexing, node sharing, and partitioning.

Publication date:
July 2009


Chapter 1. Introduction

The need to build more and more complex systems is increasing. We're trying to automate all kinds of business processes and implement complex business decisions. However, these processes and decisions are not very well represented using traditional programming languages such as Java or C#. Instead, we should use specialized technology such as the Drools platform.

In this chapter, we'll look at why there is a need for the Drools platform, what advantages and disadvantages it brings, and when (not) to use it. We'll briefly look at its history and what modules it consists of. We'll also see some commercial and open source alternatives.


Problems with traditional approaches

Enterprise systems usually have multiple layers. From top to bottom they are: presentation layer, business logic layer, and persistence layer. The middle layer—business logic represents the core of the application where all of the business processes and decisions take place.

The requirements for the business logic layer tend to change more often than the requirements for the rest of the application. We might be lucky when we get a complete specification, but that happens rarely. Even then, the requirements usually evolve over time and are often re-worked. As this happens, a standard solution using imperative style language (imperative programs are a sequence of commands for the computer to perform; for example, languages such as Java and C#) would quickly end up with so-called spaghetti code—lots of nested if-else statements.


It is often a good idea to document the following separately:

  • Business processes: Represent what the business does

  • Business rules: Represent decisions that the business does

  • Requirements: Represent how the system supports the business, defines goals

These areas change at different schedules, have a different degree of business user involvement, and none the less they are implemented differently.

I am referring to these three areas simply as requirements.

There is no well defined way of representing the business logic in Java or C#. What usually happens is that every application represents business logic differently.

For example, consider the following code that does some checking on customer level, customer accounts, and account balance:

if (customer.getLevel() == Level.Gold) {
    //do something for Gold customer
} else if (customer.getLevel() == Level.Silver) {
    if (customer.getAccounts() == null) {
        //do something else for Silver customer with no accounts
    } else {
        for (Account account : customer.getAccounts()) {
            if (account.getBalance < 0) {
                //do something for Silver Customer that has
                //account with negative balance

Code listing 1: Code written in standard Java (or any imperative style language).


Readers are requested to note that they should follow the text carefully. Some additions to the code are required in order to run the examples successfully.

First, the code checks if the customer is a Gold level customer and does something, then it checks if the customer is a Silver level customer, and if so, it checks if this customer has no accounts and does something in this case. If the customer has accounts, the code performs some logic for each account that has negative balance.

The point of this Java 'spaghetti code' is to give you an idea what we are trying to prevent. You may think that it doesn't look that bad. However, after a couple of changes in requirements and developers that are maintaining the code, it can get much worse. It is usually the case that if you fix one bug, you are more likely to introduce five new bugs. A lot of requirements are literally packed into a few lines of code. This code is hard to maintain or change in order to accommodate new requirements.

As more conditions are added, the performance of this system will degrade. Moreover, when we want to change the behavior of the application, we'll have to re-compile and re-deploy the whole application.

It is not only difficult to represent business logic in a imperative programming style language, but also hard to differentiate between code that represents the business logic and the infrastructure code that supports it.

For developers, it is hard to change the business logic. For domain experts, it is impossible to verify the business logic and even harder to change it.

There is a need for a different paradigm for representing the business logic.


The solution

The problem is that with an imperative style language, we are implementing both, what needs to be done (business requirements) and how it needs to be done (algorithm). Let's look at declarative style programming, such as SQL, in relational databases (other declarative style languages include, for example, Prolog or XSLT). SQL describes what we want to search, it doesn't say anything about how the database should find the data. This is exactly what we need for our business requirements.

A rule engine provides an alternative computational model. We declare rules in pretty much the same way as the business analyst does the requirements—as a group of if-then statements. The rule engine can then take these rules and execute them over our data in the most efficient way. Rules, which have all of their conditions true, have their then part evaluated. This is different from imperative style programming languages where the developer has to specify how it needs to be done explicitly (with a sequence of conditionals and loops).

If we rewrite the code from code listing 1 in a declarative manner, it might look like the following:

if Customer( level == Level.Gold )
then do something else for Gold customer

if Customer( level == Level.Silver )
and no Account( )
then do something for Silver customer who has no accounts

if Customer( level == Level.Silver) 
and Account( balance < 0, customer.accounts contains account )
then do something for Silver Customer that has account with negative balance

Code listing 2: Rules from code listing 1 written using declarative style.

Each rule represents one requirement. This is more readable and maps to business requirements more naturally.


The following is a summary of various advantages of a declarative style solution that Drools brings:

  • Easier to understand: Rules are easier to understand for a business analyst or a new developer than a program written in Java or other imperative style languages. It is more likely for a technically skilled business analyst to verify or change rules than a Java program.

  • Improved maintainability: As rules are easier to understand, a developer can spend more time solving the actual problem. We don't care about how to implement a solution. We only care about what needs to be done to solve a problem.

  • Deals with evolving complexity: It is much easier to add new rules, modify or remove existing rules than to change, for example, a Java program. The impact this has on other rules is minimal in comparison with an imperative style implementation.

  • Flexibility: It deals with changes to the requirements or changes to the data model in a much better way. Changing or rewriting an application is never an easy task. However, thanks to formalism that rules bring, it is much easier to change rules than to change a Java program.

  • Reasonable performance: Thanks to the Rete algorithm that is behind Drools, in theory, the performance of the system doesn't depend on the number of rules. Because a rule engine is essentially a generic if-then statement executor, there are numerous performance optimizations that can be applied independently of the rules. With every release of Drools, the performance of the engine is getting better, by adding various optimizations such as Rete node sharing, node indexing, parallel execution.

  • Requirements can be naturally translated into rules: The representation of business rules is consistent. For example, let's take some business rule and implement it in Java. Developers, depending on their experience, tend to use different ways to solve a problem. We'll find out that the possible solutions will wary greatly. Whereas with rules, this diversification becomes less apparent. It is simply because we are expressing 'what' instead of 'how'. As a result, the code is much easier to read even by new developers.

  • Ability to apply enterprise management to our rules: This builds on the previous advantage of consistent representation. If we have consistent representation, it is much easier to introduce new features that apply across all of our rules (for example, auditing, logging, reporting, or performance optimizations).

  • Reusability: Rules are kept in one place (separation of business logic from the rest of the system), which means easier reusability (for example, imagine you've written some validation rules for your application and later on there is a need to do some batch imports of data; you could simply reuse the validation rules in you batch import application)

  • Rules model the application invariants more closely: Imperative style solutions tend to impose arbitrary and often unnecessary ordering on operations depending on the algorithm chosen. This then hides the original invariants of the application.

  • The Drools platform brings unification of rules and processes: It is easy to call rules from a process or vice-versa.

  • Independent Lifecycle: Rules and processes tend to change far more often than anything else in the application. With Drools, the rules and processes can be authored, deployed, versioned, managed, and so on, independently from the rest of the application.

  • Embedability: Drools can be easily embedded into existing applications in order to implement just a section of a system.


On the other hand, don't think of Drools as the silver bullet. Writing systems that make complex decisions is never an easy task. Drools just helps to make it a bit easier. You'll have to invest in training developers. Failing to do so can result in inefficient rules and seemingly unpredictable results. The developers need to adopt a different way of thinking in order to write business rules declaratively. It may look difficult at first but once we master this, the rules will be much easier and faster to write. If we look again at the SQL/Database analogy—SQL queries require developer training in order to be efficiently written, in the same way as rules do. Also, the quality of the data model is directly proportional to the easiness of writing SQL queries and their efficiency, in the exact same way that the quality of the domain model is directly proportional to the easiness of writing rules and their efficiency

We don't specify how the business rules should be implemented, and instead we just specify what needs to happen. Therefore, we don't know how it happened, and hence it may be difficult to troubleshoot. This is a valid point and to resolve this Drools comes with a variety of tools that greatly help you with troubleshooting. Thanks to these tools, troubleshooting becomes a piece of cake.

When you are debugging a program written in Java, you can easily step through the program flow and find out what is going on. Debugging of rules can be more difficult without an understanding of how the underlying system works. Rule engines have many advantages, but on the other side they can be dangerous if you don't know exactly what's going on. In this book, you'll learn just that.

Another disadvantage of a rule engine is its memory consumption. This is the price rule engines have to pay for being efficient. A lot of calculations are being cached to avoid processing them again. However, this is no longer a problem as memory is so cheap nowadays.

Interaction of rules can be quite complex, especially, when some rules modify data that other rules depend on—it can easily cause recursion. The Drools platform provides many ways to prevent this from happening. This is where Drools Flow module comes in action. It can provide a well defined flow of program execution and can separate rules into groups that can be sequentially executed. Integration testing can also help here.

However, it should be stated that the requirements are to blame for this recursion most of the time. A well written rule does only what the business requirements specify. If the requirements are ambiguous, then the resulting rules will be ambiguous as well, potentially causing painful debugging.

When not to use a rule engine

You probably don't need a rule engine:

  • If your project is small, possibly with less than 20 rules, then a rule engine would probably be an overkill. However, think twice before making a decision because many systems start small but as more requirements are implemented, they suddenly become unmanageable.

  • If your business logic is well defined/static and doesn't change often, you don't need to change rules at run-time.

  • If your rules are simple, self-contained, and usually spanning only a single object (for example, a check that user's age is less than 21). If in pseudo-code you don't have more than two nested if-then statements. Again, consider this carefully because every system grows in complexity over time.

  • If performance is your primary concern. Are you implementing some algorithm where you want to have precise control over its execution? For example, it is not a good idea to write video code in a rule engine. Do you have a memory constrained environment?

  • If your project is a one-shot effort and it will never be used again or maintained over time.

  • If you don't have the time and money to train your developers to use a rule engine. If developers have no prior experience with logical programming, you need to include it in your time planning. It can take a few weeks to get used to the syntax and start writing rules. It is always good if a more experienced Drools developer reviews the code. The use of a rule engine requires investment at the start; however, in the long term, it brings all of the benefits that we've discussed.

If you answered yes to any of these questions, you probably shouldn't use a rule engine.



Drools is a Business Logic integration Platform (BLiP). It is written in Java. It is an open source project that is backed by JBoss and Red Hat, Inc. It is licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html). This book will focus on version 5.0 of this platform that was released in May 2009.

Work on Drools (the rule engine) began in 2001. From its beginning, Drools underwent many changes. Drools 1.0 started with a brute force linear search. It was then rewritten in version 2.0, which was based on the Rete algorithm. The Rete algorithm boosted Drools performance. Rules were written mainly in XML. The next version (3.0) introduced a new .drl format. This is a specific language specially crafted for writing rules. It proved to be a great success and it became the main format for writing rules. Version 4.0 of the rule engine had some major performance improvements together with the first release of a Business Rules Management System (BRMS). This formed the base for the next big release (5.0) where Drools became a Business Logic integration Platform. The platform consists of four main modules:

  1. Drools Expert: The rule engine itself.

  2. Drools Fusion: Complex Event Processing (CEP) module. It will be covered in Chapter 7, Complex Event Processing.

  3. Drools Flow: Workflow—combines rules and processes together. It will be introduced at the end of Chapter 6, Stateful Session and then fully covered by Chapter 8, Drools Flow.

  4. Drools Guvnor: A Business Rules Management System (BRMS). It won't be covered in this book except for testing and rule analysis in Chapter 10, Testing.

  5. Drools Solver: This is an optional module. It's a search algorithm built on top of the Drools rule engine to solve planning problems (for example, creating timetables). It won't be covered in this book.

Another very important part of Drools is its Eclipse plugin. It greatly helps with writing and debugging rules and processes. It checks for syntax errors, offers auto completion, and has lots of other useful features.

Drools has a very active and friendly community. It is growing every year. You can get in touch with this community by visiting the Drools blog, wiki, or the mailing lists. For more information, please visit Drools web site at http://www.jboss.org/drools/.


Alternatives to Drools

For completeness, we'll also mention alternative rule engines/expert systems. These include commercial products such as ILOG (now IBM)—JRules, Fair Isaac—Blaze Advisor, Corticon's BRMS, Haley (now Oracle) Business Rules Engine, Pegasystems—PegaRules, Production Systems Technologies—OPSJ, Innovations Software. Some products for the .NET platform are: Microsoft BizTalk Server, InRule for Windows Workflow Foundation, ILOG, and Fair Isaac. Alternative open source products include CLIPS and products with dual licenses such as OpenRules or Jess.

Alternatively, you can build a rule engine yourself. It may be appropriate in some specific scenario, but most of the time you'll only be re-inventing the wheel. More importantly, your solution probably won't be as efficient as an existing mature product such as Drools.



We've learned why there is a need for a BLiP such as Drools, what problems it is trying to solve, and in what way it is trying to solve them. We've seen the advantages and disadvantages of this solution.

Drools provides a different computational model for business process and rule execution. It is a generic algorithm with generic optimizations to provide 'good enough' performance while giving us lots of benefits such as flexibility and declarative programming.

We know that this platform consists of multiple modules and in the following chapters we're going to look at them in more detail, starting with the core rule engine itself—Drools Expert.

About the Author

  • Michal Bali

    Michal Bali, freelance software developer, has more than 8 years of experience working with Drools and has an extensive knowledge of Java, JEE. He designed and implemented several systems for a major dental insurance company. He is an active member of the Drools community and can be contacted at [email protected]

    Browse publications by this author
Drools JBoss Rules 5.0 Developer's Guide
Unlock this book and the full library for FREE
Start free trial