Drools JBoss Rules 5.X Developer's Guide

5 (1 reviews total)
By Michal Bali
  • 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
  1. Programming Declaratively

About this book

Writing business rules has always been a challenging task. Business rules tend to change often leading to a maintenance nightmare. This book shows you various ways to code your business rules using Drools, the open source Business Rules Management System.

Drools JBoss Rules 5.X Developer's Guide shows various features of the Drools platform by walking the reader through several real-world examples. Each chapter elaborates on different aspects of the Drools platform. The reader will also learn about the inner workings of Drools and its implementation of the Rete algorithm.

The book starts with explaining rule basics, then builds on this information by going through various areas like human readable rules, rules for validation, and stateful rules, using examples from the banking domain. A loan approval process example shows the use of the jBPM module. Parts of a banking fraud detection system are implemented with the Drools Fusion module which is the complex event processing part of Drools. Finally, more technical details are shown detailing the inner workings of Drools, the implementation of the ReteOO algorithm, indexing, node sharing, and partitioning.

Publication date:
May 2013


Chapter 1. Programming Declaratively

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 (for example, insurance-claim adjudication, subscriber enrollment, retail-pricing, promotion, banking-mortgage application, and fraud detection). However, these processes and decisions may not be represented well using traditional programming languages, such as Java or C#. Instead, we should use a specialized technology, such as the Drools platform.

In this chapter we'll look at why there is a need for a platform such as Drools, what advantages and disadvantages it brings, and when or not to use it. We'll briefly look at its history and what modules it consists of.


Problems with traditional approaches

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

For example, consider this 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)

First, the code checks if the customer's level is Gold and does something, then it checks if the customer's level is Silver, 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 a negative balance.

The point of this Java "spaghetti code" is to give you an idea about 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 who 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 several new bugs. Lots of requirements are literally packed into few lines of code. This code is hard to maintain or change to accommodate new requirements.

It is not only difficult to represent business logic in an imperative programming style language, but it is 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 the 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, for example, the SQL in relational databases. The 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 computation model. We declare rules in pretty much the same way as the business analyst does requirements, that is, 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 that have all their conditions true have their then part evaluated. This is different to imperative-style programming languages where the developer has to explicitly specify how it needs to be done (with sequence of conditionals and loops).

If we rewrite code from Code listing 1 in a declarative manner, it might look something like this:

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.

It is also useful to note that in an imperative program, the piece of code evaluating the customer's level in the first example needs to be explicitly invoked, passing to it a specific customer. In a declarative program you cannot invoke a given rule directly; do not decide on which data you want to run it, because the customer instance is actually taken from a working memory (this will be described later).


The following is a summary of the 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 language. It is more likely for a technically skilled business analyst to verify or change rules than a Java program.

  • Improved maintainability: Since rules are easier to understand, a developer can spend more time solving the actual problem.

  • Dealing with evolving complexity: It is much easier to add new, 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 better with changes to the requirements or changes to the data model. Changing or rewriting an application is never an easy task. However, thanks to the 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. 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, and so on. All this benefits new as well as old rules.

  • Translating requirements 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 vary 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 our rules (for example, auditing, logging, reporting, or performance optimizations).

  • Reusability: The 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, so you could simply reuse the validation rules in your batch import application.

  • Modeling the application closely: Rules model the application invariants more closely. The 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.

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

  • Redeploying: It is possible to change/redeploy rules and processes without even stopping the whole application.


On the other side 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 the training of developers. Failing to do so can result in inefficient rules and seemingly unpredictable results. The developers need to adopt a different way of thinking to write business rules declaratively. It may look difficult at first, but once we master this, then the rules will be much easier and faster to write.

You may be thinking that since we don't specify how the business rules should be implemented, we just specify what needs to happen, and so 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.

When you are debugging a program written in Java, you can easily step through the program flow and find out what is going on. The 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. And in this book you'll learn just that.

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

The interaction of rules can be quite complex, especially when some rules modify data that other rules depend on, which can easily cause recursion. The Drools platform provides many ways to prevent this from happening.

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, it suddenly becomes unmanageable.

  • If your business logic is well-defined or static and doesn't change often; you don't need to change rules at runtime.

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

  • If the 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 a video codec 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 declarative programming, you need to include it in your time planning. It can take few weeks to get used to the syntax and start to write rules.

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.5 of this platform that was released in November 2012.

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 domain-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 first release of Business Rules Management System (BRMS). This formed the base for the next big release 5.0, where Drools became a BliP. The platform consists of four main modules:

  • Drools Expert: This is a rule engine itself.

  • Drools Fusion: This is a complex event processing (CEP) module. It is will be covered in Chapter 7, Complex Event Processing.

  • jBPM: Workflow combines rules and processes together. It will be introduced at the end of Chapter 5, Creating Human-readable Rules and then fully covered in Chapter 8, Defining Processes with jBPM.

  • Drools Guvnor: This is a BRMS. It won't be covered in this book except for testing and rule analysis in Chapter 10, Testing.

Drools has several optional modules. For example, OptaPlanner for solving planning problems or Drools Chance that adds uncertainty support. Another very important part of Drools is its Eclipse plugin.

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



We've learned why there is a need for a business logic integration platform such as Drools. What problems it is trying to solve and in what ways it is trying to solve them. We've seen advantages and disadvantages of this solution.

In the following chapter we're going to look at how to set up the development environment before starting with some basics needed to write and execute rules in Drools.

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

Latest Reviews

(1 reviews total)
Book Title
Access this book, plus 7,500 other titles for FREE
Access now