Search code examples
drools

Is there an advantage of first binding a variable and than using it in an expression in the same pattern?


I want to know is first binding a variable and then using it in an expression in the same pattern better than first doing the expression without doing the binding and then if the expression evaluates to true do the binding so we have the value available in the next patterns or the then part.

For example we have the next three cases:

rule "first doing binding and using that value for the expression"
   when
       Pattern1($var : var, $var > 10, $var < 20)
   then
       System.out.println($var);
end

rule "first doing binding and using the value from the original variable"
   when
       Pattern1($var : var, var > 10, var < 20)
   then
       System.out.println($var);
end

rule "first doing expression with using the value from the original variable and then doing the binding if the expression is evaluated to true"
   when
       Pattern1(var > 10, var < 20, $var : var)
   then
       System.out.println($var);
end

To me the last case makes the most sense but i wanted to see an opinion.

And also would it make any sense to do the binding if the variable is not required outside of the pattern?


Solution

  • This is mostly a matter of taste. My opinion:

    • If you don't need the field value elsewhere, don't bind a variable. (Objective argument: it just clutters the code and makes you wonder whether it is used elsewhere.)
    • Stick to a "standard" pattern, which is either binding and constraints in one phrase, or make the binding followed by a constraint phrase using the field (not the variable)
    • Use a single expression for multiple similar (!) constraints on one field

    So my preferred ways would be:

    Pattern1( $var: var, var > 10 && < 20)
    Pattern2( $var: var > 10 && < 20)
    

    Note that #1 permits you to group bindings with bindings and constraints with constraints, which might be more readable.