Skip to main content

Your First DRL Rule

Let’s create a simple loan approval rule to demonstrate the basics of DRL. This example will help you understand the fundamental structure and components of Drools rules.

Step 1: Set Up Your Project

First, create a new Java project with the required dependencies. If you’re using Maven, add the following to your pom.xml:

Step 2: Create Your Fact Model

Let’s define simple Java classes that our rules will work with:

Step 3: Create Your First DRL File

Create a file named loan-rules.drl in the src/main/resources directory:

Step 4: Create Your Rule Unit Class

Now create the Java class that implements the rule unit:

Step 5: Create a Test Application

Finally, create a simple Java application to test your rules:

Step 6: Run Your Application

Execute the LoanRulesTest class. You should see output showing which rules fired and the final state of each loan application.

Basic Rule Structure

Let’s break down the structure of a DRL rule:

Components Explained:

  1. rule "Rule Name": Every rule starts with the rule keyword followed by a unique name in double quotes.
  2. Attributes: Optional specifications that modify rule behavior, like priority (salience), activation timing (date-effective), etc.
  3. when: Marks the beginning of the conditions section.
  4. Conditions: Patterns that match facts in working memory. In our loan example:
    This pattern:
    • Binds the matching LoanApplication object to variable $application
    • Searches the applications data source
    • Matches only applications with a credit score of 700 or higher
  5. then: Marks the beginning of the actions section.
  6. Actions: Java code that executes when the conditions are met. In our example:
    These actions modify the matched fact by setting properties.
  7. end: Marks the end of the rule.

Common Rule Patterns

Let’s look at some common rule patterns:

1. Simple Constraint Matching

2. Multiple Constraints

3. Multiple Patterns

4. Nested Property Access

Common Use Cases for DRL

DRL excels in a variety of business scenarios. Here are four important use cases where Drools really shines:

1. Validation Rules

Rules can validate data against business constraints and requirements.

2. Classification Rules

Rules can categorize data based on multiple criteria.

3. Decision Making

Rules can determine values and outcomes based on sophisticated criteria.

4. Workflow Routing

Rules can determine the next steps in a business process.

Next Steps

Now that you’ve created your first DRL rules and understand the basic patterns, you’re ready to explore: For hands-on practice with more complex scenarios, explore our Rule Unit Guide and Decision Tables Tutorial.