Drools syntactic sugar

Drools provides all sorts of special syntactic features. As much as we'd like, all of them won't fit in this book and more features are added constantly. Some of them, however, come in very handy when having to define our rules in a simple and comprehensive manner. We'll discuss the top three of these extra features, as follows:

  • Nested accessors for the attributes of our types
  • Inline casts for attributes of our types
  • Null-safe operators

Nested accessors

Nested accessors allow us to simplify our conditions when we have to define conditions on nested beans. Using parentheses, it allows us access the nested properties without having to redeclare the path to get to them. Let's see the following example to fully understand it:

OrderLine( item.cost < 30.0, item.salePrice < 25.0 )

In the previous condition, we're filtering order lines that have an item with a cost under 30 and a sale price under 25. We could simplify the expression using nested accessors, as follows:

OrderLine( item.( cost < 30.0,salePrice < 25.0) )

This allows us to access multiple properties of the item attribute, without having to rewrite the path to reach these properties.

Inline casts

Inline casts allow us to quickly filter properties in a type without having to abuse from clauses. It allows us to cast an attribute of a type to a specific subclass and add a condition that would only make sense after casting. Let's see the following example to clarify it:

Order(customer#SpecialCustomer.specialDiscount > 0.0)

Here, we used the # symbol to mark our inline cast. We have a customer associated with our order. For some cases, the customer will not be of the Customer type, but a subclass of it called SpecialCustomer. This type of specialized customer has a special discount attribute. In the previous condition, we're trying to filter the orders that have a SpecialCustomer type of object and for these cases, the ones where the special customer has a discount greater than zero. Using inline casts, we can check all of these conditions in a single line.

Null-safe operators

Null-safe operators are very useful when dealing with possibly incomplete models, where we might not have to write the null-checking conditions over and over again. Using a special character, we can make sure that the conditions we write on attributes are only checked if the attribute is not null. Here's a case where we're using the null-safe operators to access the category of the customer of an order:

Order(customer!.category != Category.NA)

The previous condition, without null-safe operators, would be similar to the following:

   Order(customer != null, customer.category != Category.NA)

For deeply nested attributes, the null-safe operator allows us to save a lot of writing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.162.201