Home Business & Other Mastering JBoss Drools 6

Mastering JBoss Drools 6

By Mariano De Maio , Mauricio Salatino , Esteban Aliverti
books-svg-icon Book
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Rules Declarative Nature
About this book
Mastering JBoss Drools 6 will provide you with the knowledge to develop applications involving complex scenarios. You will learn how to use KIE modules to create and execute Business Rules, and how the PHREAK algorithm internally works to drive the Rule Engine decisions. This book will also cover the relationship between Drools and jBPM, which allows you to enrich your applications by using Business Processes. You will be briefly introduced to the concept of complex event processing (Drools CEP) where you will learn how to aggregate and correlate your data based on temporal conditions. You will also learn how to define rules using domain-specific languages, such as spreadsheets, database entries, PMML, and more. Towards the end, this book will take you through the integration of Drools with the Spring and Camel frameworks for more complex applications.
Publication date:
March 2016
Publisher
Packt
Pages
330
ISBN
9781783288625

 

Chapter 1. Rules Declarative Nature

We developers have always had to deal with the complex problems in software development and they're not going to get any simpler in the future. Systems such as fraud detection software, shopping carts, activity monitors, credit and finance applications, and generally any type of systems that take isolated pieces of data and make a decision based on this information is a very common thing nowadays. Not only is there a necessity to correlate all this data, but also do it as fast as possible for more data each time, and be able to update the correlation mechanisms in a quick manner.

Great expectations spring from this sort of system, of which one of the most trending right now is the Internet of Things. As more and more devices and pieces of software interconnect, a great necessity arises for the systems that allow complex situations to be detected in a simple collaborative way by more and more people outside the development cycle, and be able to react quickly upon detection of these situations. Traditional programming has strived to adjust to this ever-changing pace of adaptation, through agile methodologies and continuous delivery. However, when it comes to the task of actually creating the software that has to detect complex situations and react to them by making a decision, the necessity for a new paradigm for development arises and that's where business rules and Drools come to our aid.

In this chapter, we will cover a detailed explanation of business rules:

  • The definition and structure of business rules

  • The importance of business rules to the development life cycle

  • The uses of technologies such as Drools and its tooling for the developers and everyone in an organization

 

What are rules?


Our everyday life is driven by rules. Every time we stop at a red light while driving, we do so as we're following a rule that says we should stop when the light turns red. We all also know the rule that states that when we are of a specific age, we are allowed to take a test to get a driving license.

Even if we don't follow these rules, like the daredevil developers we all are, we're still bound by the rules of nature; if you don't breathe in oxygen, you asphyxiate. If you jump, you're going to touch the ground eventually as the rules of physics determine that gravity will pull you down. Some of these rules (like gravity) have been studied so much that they can be expressed as simple mathematical equations. However, for our everyday rules that we consider common sense, we use a simpler structure: for a group of conditions that we detect, we take specific actions.

These sort of structures are very important for organizations as they have to deal increasingly with complex scenarios. These scenarios are composed of a large number of individual simple decisions, which work together to provide a complex evaluation of the full picture. This complex evaluation starts with simple assessments used to determine the nature of our environment that we will call inferences. These inferences might be crossed with other pieces of data or more inferences until a complex view of the domain can be achieved, understood, and actions can be taken for the benefit of the organization's goals.

These implied decisions were, for a long time, a part of the systems of an organization through very static structures. Starting with the mainframe applications, evolving over time as services, web applications, and middleware solutions, these solutions always had a high coupling with the rest of the system. business rules, on the other hand, allows for a specific, easy-to-read, and split structure to be used to define these decisions in a way that make sense to different groups in an organization—and not just the development areas—and can be quickly implemented and updated automatically.

Rules basic structure

Depending on the specific syntax of each rule engine, the syntax might vary a bit. Nonetheless, there are primal structures that are common to all the rule engines and they look something similar to the following:

when a condition is found to be true,
then an action is executed

We can add as much syntax sugar on top of this as we can think of; however, this basic structure is what lies underneath it all: a list of conditions and actions. A condition is basically a constraint or filter. These filters will look at the information available in a domain to try and find data that meets the defined criteria. Once a group of data is obtained matching the condition, an action or consequence is scheduled to be executed, taking the matching data as a parameter.

A condition always works like a query; it narrows data from a specific domain by specific filters. This means that a rule will make sense in a specific domain: If your rules are designed to filter apples and the only data you feed these rules are oranges, the rules will never find their conditions to be true.

As simple as this structure might be, it is the basis of all the business rules that we will see in this book. Thanks to this structure, business rule systems provide a great advantage over the conventional code for defining complex scenarios. Over the next sections, we will explain these advantages.

Declarative approach

The business rules are based on a programming paradigm called Declarative Programming. This paradigm sustains that you can express the logic of a program without having to explicitly describe the flow of instructions that must be followed. Since the condition works as a filter, whenever data is introduced to the rule engine that matches a condition, a rule or group of rules is determined to be executed.

This means that the control of the flow is neither determined by the order of the rules nor by the order of the incoming data, but by the conditions the rules declare. This declarative approach allows any number of rules to be written without having to worry about any specific place where they need to be written.

Imperative versus Declarative implementation

Imperative programming is the name we give to our everyday programming paradigm. This type of programming is used by languages such as Java, C#, Perl, and many others. It is defined by the control of the sequence flow of instructions, we explicitly inform when each code instruction should be executed.

The declarative approach, on the other hand, doesn't allow a direct control of the sequence flow to the developer, instead it lets the data guide the rule that should be executed. At first, this might seem hard to grasp or be considered as a useful trait for a language. However, we're about to see how Drools allows a very useful union between declarative implementations based on Drools rules and imperative implementations based on Java.

Of course, these Drools-based rules will have to be run on a Java application, where the sequence flow of the steps to be executed is determined by the code. In order to achieve this, the Drools rule engine transforms the business rules into execution trees, as shown in the following image:

As you can see in the preceding image, each rule condition is split in small blocks, connected and reused within a tree structure. Each time data is fed to the rule engine, it will be evaluated in a tree similar to this one and reach an action node, where they will be marked as data ready for executing a specific rule.

This transformation from business rules to execution tree is possible as the Business Rule structures are excellent for representing themselves as data. This means that the very code of the rules can be quickly transformed into very performing execution structures and also updated and changed during runtime. This happens because every condition can be easily added, moved, or deleted by changing the tree structure.

Tip

It is worth mentioning that, however, the previous image is just an example. The actual decision tree that is generated is a more complex topic, which we will cover in the following chapters. The previous image is just to show the objective of the decision tree.

In the next section, we will discuss the reasons these structures are very useful for performance, collaboration, and maintenance of complex systems.

 

Why do we use rules?


At this point, you might be still a bit puzzled about why rules are something useful. If we think of it, in terms of one rule or a few, we might consider it better to do it directly on the imperative code like Java, for example. As developers, we're used to break down the requirements into a list of steps to be followed and having to give away that control can be something intimidating.

However, the main strength behind business rules doesn't come from one rule or a small group of rules, it comes from a large, ever-changing group of rules that define a system so complex that it would require extensive work to maintain it if we did it with regular code.

Many rules can work together to define complex systems as the growth of the business rules code base happens organically. Whether we need to implement new requirements, modify existing ones, replace parameters, or change the structure of our system behaviour in new unexpected ways, the only thing we will need to do with the rules is implement new rules that now apply and remove the ones that don't apply anymore. This is possible as business rules work on the following principles:

  • They're independent

  • They can be easily updated

  • Each rule controls minimal amount of information needed

  • They allow more people of different backgrounds to collaborate

Rules independence

A Business Rule, all by itself, can't do much. The biggest strength of a business rule-based system is created by having a lot of rules interacting with each other. This interaction, however, is not something the rule should directly know most of the time. That's what we mean when we say rules should be independent. Each rule should be able to detect a particular set of circumstances and act upon it without needing anything other than the data of its domain.

When we think about it, this is the usual way the rules exist once we start formalizing them. Take any law book that you can find and you will see them represented as a group of rules, each one in the form of a clause. Most of them just present a scenario and any specific action or interpretation of that scenario. Most of these clauses won't mention any other clauses. There are a few that do; however, they tend to be the exception. There is a reason for it to be this way and it is to make the rules easier to understand, define, and make them less prone to misinterpretation.

The same principle applies when we define business rules for an organization. Each rule should try not to depend on any other specific rule. Instead, rules should depend only on the data provided by the domain. This allows a rule to be able to make sense by itself, without having to create any other explanation besides the content of the business rule.

However, sometimes rules do depend on others in an indirect way. The assumptions we make on one rule can be used in the conditions of another one. These data creations, through assumptions that a Business Rule engine can make, are called inferences and they are of great use to extend the usability of our rules.

Rule execution chaining

As we mentioned in the previous section, a good Business Rule is an independent entity, depending on nothing but the domain data to make sense. This doesn't mean that each rule should work on completely different data structures. Otherwise, you might end up with very complex rules that would be hard to maintain.

If a rule is too complex, it can be divided into smaller rules; however, even in said case, the independence of rules is still important and you shouldn't have to explicitly invoke rules from each other. That would imply control of the sequence flow and we've already stated that declarative programming doesn't allow this.

Instead, we can split complexity by defining the rules that make assumptions about the base domain and add information to the domain. These assumptions are called inferences. Later on, other rules can use this new information, regardless of how it is determined, as a part of their conditions. Let's see the following example to completely understand this splitting of rules:

  • When we get a signal from a fire alarm, we infer that there is a fire

  • When there is a fire, we call the fire department

  • When the fire department is present, we let them in to do their work

Each one of these three rules can be condensed into a single, more complex rule: when we get a signal from a fire alarm, we call the fire department and let them in to do their work. However, by splitting the rules into simpler components, we can easily extend the abilities of our rule engine. We could reuse the first inference that we make—about there being a fire—to trigger other actions such as activating the emergency sprinklers, disabling the elevators, or calling our insurance company.

When a rule no longer makes sense, we can remove it from the rule engine. If a new rule is required, we can create it and take advantage of the already available inferred data. As the sequence flow will be controlled by the engine, we don't have to worry about the order in which things are going to be executed or where the new rules fit among the rest of the existing rules.

Atomicity of rules

As we can create more rules that take advantage of already established inferences, the simpler our rules are, the more extensible they become. Therefore, another principle of good rule writing establishes that we should try to make our rules as simple as possible to the point that they cannot be divided into anything smaller, which could still be considered a rule. This principle is called Rule Atomicity.

The atomic rules are simple to understand. They are usually designed with minimal amount of conditions to take an action or infer the occurrence of a situation. As they are independent, they still make sense by themselves. Rule atomicity, rule independence, and inference capabilities together make business rules the simplest component that we can use to define the behaviour of any of our systems. Simplicity allows a clear understanding of why the decisions are made in the system, making rules self-explanatory and allowing us to keep a track of every rule that intervened in a specific decision. This is the reason why laws have been the building blocks of the society's internal regulations for thousands of years.

Ordering of rules

We've already mentioned that rules don't follow one specific order. Sequence flow is determined by the rule engine, which means the rule engine will have to decide, based on the available data from the domain, which rules should fire and in what order. This means the order in which the rules are defined is not important, only the data in their condition is required to match a specific rule.

There are ways of ordering rules that are competing for execution under the same conditions being met in the domain. This ordering works as a second-level prioritizing for rules, with the data in the domain model being the first one needed to determine a rule to be activated. These ordering mechanisms, which we will discuss later in more technical chapters, should be for special cases only. Exceptions to the common way we define rules instead of the norm. If we find ourselves controlling every single rule and the order in which it should fire, we should rethink of the way we're writing our rule definitions.

This is something difficult to absorb by the developers first getting a glance at declarative programming. Nonetheless, it provides a lot of improvements in the way that we can accelerate both our runtime and development efforts mainly based on the fact that if the order doesn't matter, we can add rules wherever we prefer:

  • Collaboration between rules becomes simpler to manage

  • Conflict avoidance is simpler

  • More people can work on the development of rules, which makes inclusion of other areas a very real possibility

Rule execution life cycle

The rule engine optimizes the evaluation of conditions and makes sure that we determine the rules to fire in the fastest way possible. However, the rule engine doesn't execute our business rules immediately at a condition's detection unless we specify so. When we reach a point where we find a rule evaluation to be true for a group of data, the rule and the triggering data are added to a list. This is a part of an explicit rule life cycle, where we have a clear splitting between rule evaluation and rule execution. Rule evaluation adds rule actions and the data that has triggered them to a component that we will call the Agenda. Rule execution is done on command. The moment we notify the rule engine, it should fire all the rules that we have in the said agenda.

As we stated earlier, we don't control the rules that are going to be fired. It's the engine's responsibility to determine this based on the business rules that we create and the data that we feed to the engine. However, once the engine determines the business rules that it should fire, we have the control over the time when they should be fired. This is done through a method invocation to the rule engine.

Once the rules are fired, each rule that matches in the agenda will be executed. Rule execution might modify the data in our domain and if these modifications cause some rule to match with the new data, new rule matches can be added to the agenda or if these modifications cause a match to no longer be true, it will be cancelled. This full cycle will continue until no more rules are available in the Agenda for the available data or the rule engine execution is forced to stop. The following diagram shows how this workflow is executed:

This execution life cycle will continue firing all the rules that the rule engine has decided to add to the Agenda based on the rule definitions and the domain data we feed to it. Some rules might not fire and some rules might fire multiple times.

During the following chapters, we will learn how to control the rules that should fire; however, we will always maintain the principles for Business Rule writing that we already established—independence and atomicity. The more we learn about the configuration of the rule engine, the more we will trust it to do its job. For the moment, it will be a leap of faith; however, with every step, we will learn how to control the rule engine until we can be 100% sure that it will do exactly what we expect of it.

Collaboration with Rules

As the sequence flow is beyond our direct control when creating business rules, one main advantage we have is that we don't have to worry about the code placing. As all rules are independent and the sequence flow is determined by the engine at runtime, it doesn't matter where we place the rule.

With common, imperative programming languages such as Java, each instruction will happen at a specific moment in the program execution and finding said specific point in the code, where we need to add our modifications, involves reviewing the whole set of code. Entire design patterns have been created around managing this limitation in ways that we can collaborate between developers while working on the same system. Every major design pattern works on splitting the code base in groups such as modules, methods, and classes to manage these collaborations between developers with ease.

However, the main limitation with the imperative code is that once the system has been designed, we cannot break beyond the limit that we used to split our code base easily. We are forced to foresee the probable changes that might be added in the future when we create the design—something which can be very difficult to achieve. If we fail to do so and many developers have to modify the same code sections due to the different requirements, their code will be prone to conflicts.

This limitation can be avoided by declarative programming because the specific order of the rules doesn't matter. Collaborations between different people defining different aspects of a same domain module can be done without conflicts as a good place to add another Business Rule is anywhere between the existing business rules. The output execution will be relatively same, regardless of the order.

Let's take a look at the following pseudo code section comparison between the Imperative and Declarative code. When we have to add any modifications to an imperative block of code, we cannot just do it at any place. There are specific places to add a specific correction and if you place them in a different spot, it either doesn't work as expected or is not as performing as it could be, you can the comparison as shown as follows:

The business rules, on the other hand, define each rule as an isolated block of code. People could add work in any part without any problem. This makes application development with business rules easier in collaborative environments as it is far less prone to conflict problems, as shown in the following image:

Having less chance for conflict, we can concentrate our time and energies on the solution that we are trying to build instead of worrying about merging the solutions between different components or within a same component.

The increased possibility of having more points on which to add code without conflicts opens the door to have more people involved in the development life cycle. This can help speed up the development and update of our software solutions dramatically.

Involving more people with Rules using a BRMS

Thanks to the increased collaboration business rules provides us during the development time, we can have an increased amount of people working on defining the decisions for our systems. The immediately subsequent bottleneck that we usually face at this point is finding more people who understand how to write the rules.

Writing rules is, at least in the beginning, a technical task. It requires a certain level of knowledge about how to define conditions and actions—topics that we will cover in detail in the next chapters—and getting more people to learn how to write these rules takes a little time.

Even if we get technical people to learn how to write rules quickly, it is usually not enough. It's not due to a technical limitation but mostly due to the people who hold the practical knowledge that we need to write as business rules not being the most available or tech-savvy group of people. It could be the case, of course, and you may have probably found one of the best groups to work with Business Rule-based systems. However, for most of the cases, they will have the practical knowledge but not the time or desire to learn how to write technical rules.

For these groups of business experts, there are platforms that allow them to access rule writing in a more user-friendly way. These platforms are a composition of user-friendly editors, with versioning and publishing capabilities, called Business Rule Management Systems (BRMS). Basically, business experts will be able to create rules using the same everyday language that they are familiar with and use for thinking definitions for decisions. You will learn more about these user-friendly ways of writing rules in Chapter 5, Human Readable Rules. For now, let's just mention that we can define business rules in a natural language using editors that allow business experts to work directly on the rules in a very similar speed to how technical experts define business rules.

The following is a small screenshot where we can see one of these editors in the KIE Workbench, a Drools based BRMS:

Letting the rule engine do its job

So far, we've covered an introductory explanation about the structure of business rules. Whenever we had to explain how the rules were executed, we simply said that the rule engine will take care of it. When we use business rules, we trust a rule engine to determine the rules that should fire, based on the domain data that we send to it. We will, at this stage, try to define how the rule engine will define the rules that should be fired and when.

In the previous sections, we saw a brief display about how rules can be translated to execution trees, where decisions are taken based on the data, following a declarative paradigm approach. In this section, we will try to explain how this structure helps in creating the most performing execution possible based on our rule definitions.

Rule engine algorithm

The rule engine transforms the business rules that we define to an executable decision tree through a specific algorithm. The performance of the execution tree will depend on the optimization mechanisms the algorithm can generate. The Drools 6 framework defines its own algorithm focused on higher performance. This algorithm is called PHREAK and was created by Mark Proctor. It is based on a series of optimizations and redesigns of a pre-existing algorithm called RETE, created by Charles Forgy. PHREAK is one of the most efficient and performing algorithms implemented as open source to the date.

In the generated execution tree, every condition in our rules will be transformed to a node in the tree and how the different conditions connect to each other in our rules will determine the way these nodes will be connected. As we add data to our rule engine, it will be evaluated in batches, flowing through the network using the most optimized paths possible. The execution tree finishes when the data reaches a leaf, which represents a rule to be fired. These rules are added to a list, where a command will be called to fire all the rules or a subgroup of rules.

Due to this continuous live evaluation of the condition of rules, this rule engine bases its performance on having all the data for rule evaluation available in the memory. The details about how the algorithm builds a decision tree will be introduced later in this book.

Each time we add more data to the rule engine, it is introduced through the root of the execution tree. Every optimization on this execution tree works according to the following two main focus points:

  • It will try to break down all the conditions to the smallest amount of units in order to be able to reuse the execution tree as much as possible

  • It will try to make only one operation to go to the next level below, until it reaches a false evaluation of a condition or a leaf node, where a rule is marked for execution

Every piece of data is evaluated in the most-performing way possible. The optimizations of these evaluations are the main focus of the rule engine. In the following chapters, we will discuss how to make rules that take advantage of each of these advantages in order to make our business rules as fast as possible.

 

When should we use rules?


The business rules are very powerful components. They introduce a large number of changes in the way we define our business logic. They allow us to handle the complexity, performance, and maintenance of our systems in order to accomplish a lot in a very little time.

These improvements are of great value for any project and business rules can be implemented and added to any type of project that you might find out there. Nonetheless, we want to remark these projects that would benefit the most on introducing business rules to their technological stack. These projects have one or more of the following characteristics:

  • They define a very complex scenario that is difficult to fully define even for business experts

  • They don't have a known or well-defined algorithmic solution

  • They have volatile requirements and need to be updated very often

  • They need to make decisions fast, usually based on partial amounts of data

Complex scenario, simple rules

Every once in a while, we find systems—or parts of systems—where small relations among components start having more importance the more we investigate them. At first, they might seem innocuous components that take very little decisions based on small relations between two or three sources of data. As we start investigating them further, these relations take on more and more importance. Eventually, we might find the relationship between the parts produces more collective behaviors that even the business experts were unaware could happen; however, this still make sense. These kinds of systems are called Complex Systems and they are one of the places where business rules provides a great aid.

Complex scenarios are usually defined by small statements. The full picture, involving every single composition, aggregation or abstraction of data needed to completely define the scenario, is usually something beyond our initial grasp. Therefore, it is common that such systems start being defined through partial explanations. Each small relation in the system gets defined as a different requirement. When we analyze each one of these requirements, on splitting them into their most basic elements, we find ourselves defining business rules.

Each Business Rule helps in defining every small component of a complex scenario. As more and more rules are added to the system, more and more of these relations can be handled in a simple-to-read way. Each rule then becomes a self-explanatory manual for each small decision that the system takes when executing our complex scenario.

The examples of complex applications can be very varied, as follows:

  • Fraud detection systems: Usually they take information from every transaction done within a central service and investigate the correlations between them to determine situations that are unlikely to come from an honest and legal use of the system. Things such as unusual credit card operations, large amounts of activity in usually stable accounts, and unexpected parameters in transactions are usually the things searched by these systems.

  • Customized retail coupons for returning clients: In all kinds of commercial activities, client fidelity is always valued. A usual strategy to maximize it is through special coupon generation based on the client's shopping habits. To accomplish the right coupon, a complex system needs to evaluate the purchase history of the client, frame the client in a specific demographic subgroup, and select the best offer available for this subgroup. All these things need to be done based on the complex relations between different purchases and their tendencies.

  • Credit scoring software: Credit scoring is a numerical expression based on a level analysis of a person's credit files to represent the person's credit worth. Every debt, credit, purchase, or relation can be a valid source of data to determine the scoring of a person. The complexity of this scenario comes from having to correlate, weigh, and return a specific score for a person based on the correlation of all these sources of data.

Ever-changing scenarios

Even when we don't have a complex scenario in our hands, we might still benefit a great deal from defining our application's logic using business rules. If the elements involved in making a particular decision tend to change very frequently, business rules can be a good solution for managing such volatility in the behaviour of a system.

The business rules are represented in the rule engine as a data tree. In the same way that we can modify the elements of a list, we can remove or add a Business Rule from a rule engine. This can be achieved without having to restart our application or reinstalling any components. Internal mechanisms provided by the Drools 6 framework can be used to update the rule definitions automatically from external sources. The tooling provided by Drools 6 is also prepared to provide update mechanisms for the business rules from user-friendly editors. The complete architecture of the Drools 6 API is based on making this as adaptive as possible.

If we find a system where the requirements might change very frequently, even in a daily or hourly frequency, business rules may be the best fit for such requirements due to its update capabilities, regardless of the complexity of the system.

Example–eShop system

Along the rest of the book, we will work on a set of decision services based on business rules with a common domain: an eShop application. Practise is a crucial component of learning about a new framework and in order to make it simple in order to go into detail on the rule engine as fast as possible, we will define a basic model shared between most of our examples.

To start with, we will define the model of our eShop system. This model will contain all the different things that are relevant to make decisions about our application. Some of these objects are as shown in the following:

  • Product: Our shop will sell different kinds of items. Each kind will be represented by a product object, containing the details about the specific item.

  • Stock: This is the amount of each product that we have in storage.

  • Provider: Our products come from different providers. Each one of them can provide the eShop with specific kinds of products in a specific capacity for delivery.

  • Provider Request: When we run low or out of a specific product, we will have to create a request for our providers to fill our stock.

  • Client: The shop has clients that will have preferences for specific products, pending and completed orders, specific demographic information, payment preferences, and any type of data that we can obtain from their navigation on our eShop.

  • Order: When a client likes one or more products in our eShop, they can order them to be delivered. The orders have different status, depending on whether the client received it successfully or not. They also have information about its specific products and their quantity.

  • Discount: The eShop offers different types of discounts, depending on the type of purchase.

  • Sales channel: The eShop that we will emulate can work with multiple sites and each one of them is treated as a different sales channel. Each sales channel will have its own specific target audience, which is determined by the clients who use it.

As we need more types of objects to define the reality of our eShop, we will define more classes to extend the understanding of our world. Once we start correlating all these pieces of domain data together, we will be able to detect all types of situations and act upon them in the benefit of both our eShop and its clients. Some of the things that we will be able to do are shown in the following:

  • Defining the best sales channel for a specific kind of product by correlating products with each sales channel and comparing them with the rest of them. Based on this information, we can create custom discounts for the products in these channels.

  • Defining the client preferences for specific products. Based on this information, we can offer them discount tickets tailored for their specific tastes.

  • Determine the average consumption of specific products and compare them with our stock. In case of necessity, we can automatically trigger provider requests.

  • Based on how many orders we have in process for specific providers, we can ask for a discount on the price.

  • We can analyze the different purchases that our clients make in our eShops. If, at some point, the purchases go beyond what we consider normal, we can take a series of actions, from a simple warning to providing direct human support for a specific purchase.

These are just a few things that we could do with business rules for such domains. As we find more situations with specific requirements to be fulfilled, we will learn new techniques to write our rules and configure our runtime. Each new necessity will guide us to define new components in order to get the most out of the Drools 6 framework.

 

When not to use a rule engine


Every project, in one way or another, can benefit from using business rules. They are highly performing, easy to change, and self-explanatory software components. However, there are a group of conditions that a project might have that would make use of business rules a bit of overkill. Some of the characteristics that make a project benefit the least from business rules are shown in the following:

  • There are very few, self-contained rules involved in the project: If the business rules identified in the requirement gathering are very simple and span about one or two objects at most, we don't need a rule engine to run them. A good rule of thumb is that if we can write the business rules that we need as the pseudo code in less than a page and with less than two nested if-then clauses, we might not need a rule engine at this particular time.

  • The business logic doesn't change often: If changing rules at runtime is not going to be needed but the logic is still complex, a rule engine might still be a good idea. However, if the complexity behind the rules is not that high and we can assume it will remain that way for a long time, we might not need a rule engine.

  • A very strict control of the execution flow is crucial for the application: As we stated before, a sequence-flow control is not provided when we execute our business rules. If the business logic behind the business rules depends a lot on a strict set of steps that need to be executed sequentially, business rules might not be the right fit. However, if it does change frequently, perhaps a business process would be worth considering.

It is still a responsibility of the project team to determine whether business rules might be a good fit even if these conditions are met. After all, our experience can lead us to think that the amount of rules has a big chance of growing in the future or there might be situations where the rules will eventually need to change more frequently. Each project has its own unique characteristics and it might be that a project with no need for business rules right now cannot be thought without them in the future.

 

Summary


The business rules is a very strange concept to deal with on our first encounter as traditional developers, and the purpose of this first chapter was to present how they fit in our everyday application development and why they can help us define better systems.

We've seen what rules are, defined their structure, and covered their practical uses. We've also covered a few examples of projects where rules are useful—and some other examples where they might be not necessary. We've also introduced our eShop project, which will guide us through the next few chapters in order to establish all the benefits Drools 6 provides, from Business Rule writing to Rule Engine configuration.

In the next chapter, we will start writing our first business rules and take our first steps in defining our rule-based projects.

About the Authors
  • Mariano De Maio

    Mariano De Maio is an IT consultant and software developer with over eleven years of experience in Java and open source frameworks. He has been working with Drools and jBPM for the last six years and has collaborated with the Drools and jBPM projects several items, including Infinispan's persistence modules, extensions to the jBPM APIs, and different add-ons to the tooling functionality. In 2013, he wrote jBPM6 Developer Guide for Packt Publishing, along with Mauricio Salatino and Esteban Aliverti. In 2015, he co-founded jWoop, http://www.jwoop.com, which is a company that provides consultancy and training around the world. He has participated in international conferences, such as Decision Camp and other Decision Management webinars. Mariano is based in Buenos Aires, where he is happily married to his wife, Tamara, and takes care of his beautiful daughter, Sofia. In his free time, he likes to work on contributions to the open source projects he is using. He also runs his personal blog, http://marianbuenosayres.wordpress.com, about jBPM, Drools, and Decision Management. You can find him through the official Drools IRC channel #drools at irc.freenode.net, under the nickname mariano or mariano84.

    Browse publications by this author
  • Mauricio Salatino

    Mauricio Salatino is a Senior software engineer at JBoss/RedHat. Mauricio works full time as a Drools and jBPM Core Developer and is in charge of developing the new generation Business Process Management Suite, along with contributing to the evolution of Drools and jBPM. Mauricio is the author of three Packt Publishing books about jBPM: jBPM6 Developer Guide, jBPM5 Developer Guide, and jBPM Developer Guide. Mauricio is based in London, UK, and in his spare time he likes to meet community members of different open source projects to build interesting projects.

    Browse publications by this author
  • Esteban Aliverti

    Esteban Aliverti is a software engineer and a former Drools/JBPM consultant. He is also a fervent open source promoter and developer with meaningful contributions to the JBoss Drools and JBPM frameworks for the past six years. He is the coauthor of jBPM5 Developer Guide and jBPM6 Developer Guide by Packt Publishing and was awarded the JBoss' Community Recognition Award in 2012 and 2013.

    Browse publications by this author
Latest Reviews (5 reviews total)
Nice introduction to Drools, but could really use a better editor. English is obviously not the authors first language and the text gets very repetitive. Some of the content seems a little terse and the ordering is quite strange in some chapters - again a more attentive editor could have improved it a lot.
real good knowledge base for beginners
Great book for anyone who wants to master JBoss Drools.
Mastering JBoss Drools 6
Unlock this book and the full library FREE for 7 days
Start now