Search code examples
javadrools

Unexpected output from drools rules


I've been learning Drools and I implemented a simple program. However, the output doesn't give the result as I expected.

Rule .drl file:

rule "Is of valid age" salience 10
    when
        $a: Applicant (getAge() > 18)
    then
        $a.setValid(true);
        System.out.println($a.getName() + " is eligible for driving license!");
end

rule "Can by alcohol" salience 1
    when
        $a: Applicant(isValid() == false);
    then
        System.out.println($a.getName() + " cannot buy alcohol!");
end

In main I insert a simle applicant object:

Applicant applicant1 = new Applicant("Berat", 20, 2010);
kieSession.insert(applicant1);
kieSession.fireAllRules();
System.out.println(applicant1.getName() + " is of valid age: " + applicant1.isValid());

When I fire all rules to this object the output is:

Berat is eligible for driving license!
Berat cannot buy alcohol!
Berat is of valid age: true

Although, I give priority of each rule with salience keyword, "Can by alcohol" rule is still fired. It should not be fired because in the first rule setValid(true) is executed and in the second rule isValid() == false control should return false so then part should be missed.


Solution

  • The statement

     $a.setValid(true);
    

    does set valid to true for the Applicant, but this isn't propagated to the Drools rule engine. You need to

     modify( $a ){ setValid( true ) }
    

    for other lower salience rules to see the correct setting.

    Retracting the fact just hides the problem.