1

Is there any possible way to avoid looping without using NO-LOOP attribute of Drools(Like I have heard we can achieve this by using the not(!) operator on objects but am unable to find out.)

The problem is NO-LOOP attribute can't be used(as that is the requirement) so refer to the rule below and tell is it possible to avoid looping.

TestClass.java

public class TestClass{
     private String name;
     private int age;

// Few other variables
// their getters and setters

}

Rules

rule "abc"
    when 
        $obj : TestClass(name=="test", age != 20)
    then 
        TestClass $obj2 = new TestClass();
        $obj2.setName("test");
        $obj2.setAge(30);
        insert($obj2);
end
Hitesh Garg
  • 1,211
  • 1
  • 10
  • 21
  • 1
    The best strategy to avoid loops is to include a constraint catching the value that is achieved by the RHS code. – laune Jan 22 '15 at 13:08

1 Answers1

2

Not sure why some folks are so afraid of no-loop. It exists for a perfectly good reason. i.e. It instructs the engine to not re-evaluate a rule if the reason for that re-evaluation is due to modifications or insertions in that rule.

However, you can do it manually through your own logic. Just insert an appropriate fact and match on it not existing.

declare IsTested
    name: String
end

rule "abc"
when 
    $obj : TestClass($name: name=="test", age != 20)
    not IsTested(name == $name)
then 
    TestClass $obj2 = new TestClass();
    $obj2.setName("test");
    $obj2.setAge(30);
    insert($obj2);
    insert(new IsTested($name));
end

A while back, Esteban Aliverti wrote a blog post on common patterns for avoiding infinite loops in Drools. It's worth a read.

Steve
  • 9,270
  • 5
  • 47
  • 61
  • Thanks @Steve - That works perfectly fine. Although i was actually using Excel sheet so it took some time to figure out how to implement this using Excel sheet. – Hitesh Garg Jan 22 '15 at 09:36
  • I'd recommend Esteban's blog on the topic to see pros and cons of different solutions https://ilesteban.wordpress.com/2012/11/16/about-drools-and-infinite-execution-loops/ – Davide Sottara Jan 23 '15 at 04:46
  • Well remembered Davide ... I have added the link to the answer. – Steve Jan 23 '15 at 09:03