user2963365
user2963365

Reputation: 91

Drools condition for when fact exists or does not exist

I'm trying to set up a drools rule that would achieve something like this:

rule "Rule 1"
    salience 100
    activation-group "..."
when
    $fact: Fact exists, or fact does not exist
then
    if $fact exists then do X. Else, do Y.

I know I can do this by having two different rules, one for when the fact exists, and one for when the fact does not exist. Is there any way I can combine these conditions into one? For the when statement, I have tried:

$fact: Fact() || not Fact()

which didn't work. Is there a correct way to write the "when" statement in drools?

Upvotes: 0

Views: 1364

Answers (1)

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15180

If we revert to boolean logic, A || !A is the same as true so you can omit the condition entirely.

You're already doing this correctly. Rule 1: if X exists, then do A(). Rule 2: if X does not exist, then do B(). That is the correct way to do things:

rule "Fact exists"
when
  exists(Fact())
then
  doX()
end

rule "Fact does not exist"
when 
  not(Fact())
then
  doY()
end

That's good rule design and how you should do this. I can't think of a good reason to compress it into one rule. If you can clarify a legitimate use case for why you'd want to collapse it into a single rule, it might be possible to give a better or more concrete response.

You may be able to abuse conditional and named consequences for this, though it's definitely not designed for this (nor recommended.)

Upvotes: 1

Related Questions