I'm new to drools and I've written some rules and they work as expected. However, I can't help but think there is a more concise way of writing these rules.
My situation is that many of the rules have a few similar basic requirements that I'm repeating in each rule. So, for instance, suppose I have the following rules:
rule "Main Valid Message"
when Account (open && valid)
then myResults.add(new Message("Your account is valid"))
end
rule "The user owns something Message"
when Account (ownership.size() >= 1)
then myResults.add(new Message("You own something"))
end
rule "Eligibility Message"
when
Account (open && valid)
Account (ownership.size() >= 1)
then myResults.add(new Message("You are eligible"))
end
Is there a way to rewrite the eligibility rule to take advantage of the first two rules instead of duplicating their content?
ANSWER: Using a combination of J Andy's and laune's replies below, I wrote it as follows:
declare IsValid
account : Account
end
declare OwnsSomething
account : Account
end
rule "Main Valid Message"
when $account : Account (open && valid)
then
myResults.add(new Message("Your account is valid"))
insertLogical(new IsValid($account));
end
rule "The user owns something Message"
when $account : Account (ownership.sizeOwnsSomething() >= 1)
then
myResults.add(new Message("You own something"))
insertLogical(new OwnsSomething($account));
end
rule "Eligibility Message"
when
IsValid()
OwnsSomething()
then myResults.add(new Message("You are eligible"))
end
One option would be to use (internal) facts to handle state. Something like this
I'm not sure what's your use case for Account ownership, but I think you'll get the point from the above code sample.
The
AuthenticatedUser
fact is now declared inside the DRL file. It could just as well be normal Java class. Also, in the example it has no properties at all, but as mentioned earlier, it could even hold some state as well which you modify in the rules.