1
votes

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.

2
I believe the behavior is correct salience defines the priority and so high salience rule executes first and then followed by anothermhasan
Since applicant object's age is over 18, setValid(true) should be executed so In "Can by alcohol" rule, isValid() == false should return false and the rule's then part should not be executed.Berat Postalcioglu

2 Answers

1
votes

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.

0
votes

I think salience only defines execution order.

You can try retract($a) in valid age rule in the then clause.