Search code examples
jbossdrools

What makes the order of this ruleset


I am currently learning Drools and reading the book Mastering JBoss Drools 6

In the beginning of chapter 4 an example is given to show the use of the delete keyword. This is that example:

rule "Init current date" 
when 
then 
   insert(new Date()); 
end 

rule "Expire coupons" 
when 
   $now: Date() 
   $cp: Coupon(validUntil before $now) 
then 
   delete($cp); 
end 

rule "Execute coupon" 
when 
   $o: Order() 
   $cp: Coupon(order == $o) 
then 
   System.out.println(" We have a coupon for this order!"); 
end

Now my question is: Why is the "Execute coupon" rule fired later than the "Expire coupon" rule. As I've learned the order of the rules are non deterministic, so I was thinking that the "Execute coupon" rule can be fired before the other two rules


Solution

  • You are right. From my experience, I'd even bet some money on "Execute coupon" firing first, because later rules are typically fired first.

    Clearly the example would have to be corrected, either by

    rule "Execute coupon" 
    when
        $now: Date() 
        $o: Order() 
        $cp: Coupon(order == $o, validUntil after $now ) 
    then 
        System.out.println(" We have a coupon for this order!"); 
    end
    

    or by using salience (which one should try to avoid, if possible).

    However (I don't have the book) I can also imagine a scenario where the rule set might work as given:

    session.insert( new Date() );
    session.insert( coupon );
    session.fireAllRules();
    
    session.insert( order );
    session.fireAllRules();