Externalizing Application Logic : Business Rules Approach with Drools
Join the DZone community and get the full member experience.
Join For Freei originally written this post in our company's blog and i decided to share it here as my first contributed article. this topic is about externalizing application logic through business rules approach using the drools business rules engine.
enterprise applications usually consists of multiple layers. primarily presentation layer, business logiclayer and persistence layer. the business logic layer is considered the heart among these layers, and this is where all processes and decisions take place. requirements for this layer also changes more often than the rest of the application. as requirements continues to change, it is very easy for the code in this layer to end up tangled in a situation known as “spaghetti code”, lots of nested if-else conditions, and as new conditions are added, readability suffers. moreover, to change the behavior of the system, a recompile and rebuild must be done.
this post aims to introduce the business rules approach , a development methodology where rules, decisions and processes are used by, but does not have to be embedded in business process management systems. you’ll be introduced to this methodology through the use of a business rule engine – jboss drools expert , part of jboss’ business logic integration platform.
what are business rules?
a business rule is simply a statement that defines or constrains some aspects of the business. business rules always resolves to either true or false. business rule can also be defined as an abstraction of the policies and practices of a business organization.
example:
- a customer can have several reservations but only one car can be rented at a time. (car rental)
- when a registration is coming from a country listed in the banned country list, reject the registration. (ptc site registration)
what is a rule engine?
a business rule engine is the heart of the technology behind the business rules approach. it is a system that evaluates and executes one or more business rules in a runtime production system against known facts (domain models).
why use a rule engine?
- logic and data separation – your data is in your domain objects, the logic is in the rules.
- speed and scalability – business rules engine uses algorithms design to efficiently match rule patterns to your domain objects, for example the rete algorithm as used in drools expert. also in terms of scalability, rules can be shared in different systems allowing us to create or integrate sub-systems that uses some of the rules used by other sub-systems.
- centralization of knowledge – since logic are externalized in the form of rules, there is only a single source of truth, and that is your repository of rules / knowledge (a knowledge base).
- explanation facility – rule systems effectively provide an “explanation facility” by being able to log the decisions made by the rule engine along with why the decisions were made.
- understandable rules – in drools expert, rules can be written using dsls (domain specific languages) allowing non-technical domain experts to write rules which are close to natural language.
sample rules
figure 1: an example drools rule file
hello message rule and goodbye message rule. we can read these rules this way:
- hello message rule – “when the message object’s status is hello, display the message attribute of the message object and change its message and status to “goodbye cruel world” and goodbye respectively”.
- goodbye message rule – “when the message object’s status is goodbye, display the message attribute of the message object.”
make your applications rules-driven
drools expert is a sub-project of jboss business logic integration platform and this is the business rule engine we’ll be using in this post. to make your applications rules-driven using drools expert, you need first to understand the following important concepts:
- facts – facts are simply your domain objects / models. rules are run against these facts to match conditions declared in the rules with the state of the fact currently being used and this determines the rule / rules to run.
-
rule – a rule is a statement that test a condition against a fact and is composed of 3 important sections:
- name – name of the rule
- lhs (condition) – this is the “when” section (see above). this section declares the condition the rule would test.
- rhs (consequence / action – this is the “then” section (see above). this section declares the consequence or the action to be performed when the condition declared in the “when” section is met.
- knowledge base – a repository of rule / knowledge
- knowledge session – a session is an established interaction between your application and the rules engine. a session is created from a knowledgebase and can be either stateless or stateful. the application uses the established session to run the engine against the inserted facts.
example code:
package com.ideyatech.drools; import org.drools.knowledgebase; import org.drools.knowledgebasefactory; import org.drools.builder.knowledgebuilder; import org.drools.builder.knowledgebuilderfactory; import org.drools.builder.resourcetype; import org.drools.io.resourcefactory; import org.drools.runtime.statelessknowledgesession; import com.ideyatech.drools.bean.message; public class main { public static void main(string[] args) { final knowledgebase knowledgebase = createknowledgebase(); final statelessknowledgesession session = knowledgebase.newstatelessknowledgesession(); try { final message message = new message(); message.setstatus(message.hello); session.execute(message); }catch (throwable e) { e.printstacktrace(); } } private static knowledgebase createknowledgebase() { final knowledgebuilder builder = createknowledgebuilder(); final knowledgebase knowledgebase = knowledgebasefactory .newknowledgebase(); knowledgebase.addknowledgepackages( builder.getknowledgepackages()); return knowledgebase; } private static knowledgebuilder createknowledgebuilder() { final knowledgebuilder builder = knowledgebuilderfactory.newknowledgebuilder(); final string rulepath = "com/ideyatech/drools/rule/hello-world-rule.drl"; builder.add(resourcefactory.newclasspathresource( rulepath), resourcetype.drl); if (builder.haserrors()) { throw new runtimeexception(builder.geterrors().tostring()); } return builder; } }
code explanation:
- the code above contains two helper methods: createknowledgebuilder() and createknowledgebase().
-
the createknowledgebuilder() method creates an instance of knowledgebuilder which is responsible for taking source files such as .drl (drools rule) files and turning them into a knowledgepackage of rule and process definitions which a knowledgebase can consume.
- in this method we added to the knowledgebuilder the rule file “hello-world-rule.drl” which is a classpath resource. take note that rules can also obtained as a file resource or a url resource.
- the createknowledgebase() method creates an instance of knowledgebase which is a repository of all the application’s knowledge definitions. this method uses the createknowledgebuilder() and gets all knowledge packages from the created knowledgebuilder to be used by the created knowledgebase.
- in the main method after creating our knowledgebase, we then created a statelesssession and then asked the created session to execute all rules against the message object with a status hello.
when we run this code, this produces the following result:
human-readable rules using dsl
in drools, rules can also be written in a syntax which is close to natural language (english for example). this allows non-technical domain experts to author rules using plain english statements and a few drools rule syntax which doesn’t require advanced technical knowledge to understand. the example below shows a simple rule written in dsl format.
figure 2: dsl file
figure 3: dslr file
in the above figures, we have 2 files; a dsl and a dslr file. the dsl file contains the mapping of the conditions and consequences used in the dslr file. for example, the dsl condition “there is a customer with firstname {name}” is mapped to “$customer : customer(firstname == {name})”. this mapping / translation simply tells the engine how to interpret the rule written in the dslr file.
conclusion
truly, by using a business rule engine and allowing business rules to drive our applications, we can increase our development agility, improve software maintainability, and allow us to deal much easier with evolving requirement complexity. however, also take note that by introducing business rule engine to your applications, you also add another layer of complexity to your application architecture. using a business rule engine should be considered when we need to create pluggable systems, expert systems or when the need to handle ever-changing requirements is very high. for application requirements of moderate complexity, the standard approach of embedding logic through imperative programming language may suffice.
Published at DZone with permission of Arjay Nacion. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments