Reputation: 5736
when writing drools rules, do I separate the checkings into more rules or group them all in one rule to have more ifs in the 'then' part? Not considering any management issues, just performance (e.g. execution time, memory usuage).
Say I have multiple tasks that their conditions and stuff-to-do are 90% similar, just 10% left are specific to each of them. Do you write
rule A
when (90% conditions) and (task 1 or task 2 or task n)
then
if (10% conditions for task 1) ...(10% stuff-to-do for task 1)
else if (10% conditions for task 2) ...(10% stuff-to-do for task 2)
else if (10% conditions for task n) ...(10% stuff-to-do for task n)
(90% common stuff-to-do)
end
or
rule B-1
when (90% conditions) and (10% conditions for task 1)
then
(90% common stuff-to-do) + (10% stuff-to-do for task 1)
end
rule B-2
when (90% conditions) and (10% conditions for task 2)
then
(90% common stuff-to-do) + (10% stuff-to-do for task 2)
end
rule B-n
when (90% conditions) and (10% conditions for task n)
then
(90% common stuff-to-do) + (10% stuff-to-do for task n)
end
Thank you!
Upvotes: 0
Views: 7855
Reputation: 1227
Instead of grouping the conditions and tasks together, you need to separate them into individual rules, like in the following example. Execution time will not matter much, thanks to RETE and memory usage mostly depends on your facts, not rules.
By separating your conditional logic into separate rules, you will gain testable and manageable code base. Putting everything into a big rule is not much different from using if-else statements in plain java code, in that case Drools will just add complexity to your project without any benefits.
rule 90_1
when
//first rule for common stuff
then
//
end
rule 90_2
when
//second rule for common stuff
then
//
end
rule 90_N
when
//last rule for common stuff
then
//
end
rule A_1
when
//first rule for A
then
//
end
rule A_2
when
//second rule for a
then
//
end
rule B
when
//rule for B
then
//
end
Upvotes: 1
Reputation: 4310
I prefer the second one. It is clean to have separate small rules. Because the purpose of Drools is to change your IF- ELSE into RULES
Upvotes: 2
Reputation: 9480
I'm no expert on Rete engines, but the general rule is that as long as decisions are on the left hand side of the rule, the engine is able to optimise its Rete tree to ensure that a decision can be reached most efficiently. So it should be more efficient to keep everything on the LHS. Same reason 'eval' in the LHS should be avoided like the plague.
And of course, stepping aside from micro-optimising rules, if each such decision is declared in a separate rule, then it's simple to write unit tests which evaluate whether the correct rules have been activated in different circumstances. If you amalgamate the rules then you're no longer able to test whether your rules are firing when they should.
Upvotes: 3