Search code examples
javadroolsrules

Drools 6.4 Multiple modify and named consequences


I am pretty new in Drools and I would like to know if is it possible to trigger the modify/update fact only when the RHS is ended.

Look for this sample :

rule "test"
    when
        $o1 : MyObject( isNew == null ) // isNew is a Boolean()
        do[initNew]
        $o2 : MySecondObject( name = "ABC" )
    then
       ... //do stuff
       modify($o1) { setNew(true) }; //set to true if we arrived here
       modify($o2) { setName("DEF") };
    then[initNew]
       ... //do stuff
       modify($o1) { setNew(false) }; //init to false
end

In this sample, I would like to set isNew to false there is no $o2 in facts, otherwise is want to set it to true.

When I test this rule, the do[initNew] is called, the modify is fired so the rule is instantly replay and the then part is never called....

An idea ?

Thanks :)


Solution

  • The lure of procedural programming has been introduced with do[] and then[]. Stick to clean logic - what you need is two rules:

    rule "test Second true"
    when
        $o1 : MyObject( isNew == null ) // isNew is a Boolean()
        $o2 : MySecondObject( name = "ABC" )
    then
        modify($o1) { setNew(true) };
        modify($o2) { setName("DEF") };
    end
    
    rule "test Second missing"
    when
        $o1 : MyObject( isNew == null ) // isNew is a Boolean()
        not MySecondObject( name = "ABC" )
    then
        modify($o1) { setNew(false) }; //init to false
    end