6.4. Function

Note

(updated to Drools 4.0)

function

Figure 6.7. function


Functions are a way to put semantic code in your rule source file, as opposed to in normal java classes. They can't do anything more then what you can do with helper classes (in fact, the compiler generates the helper class for you behind the scenes). The main advantage of using functions in a rule is that you can keep the logic all in one place, and you can change the functions as needed (this can be a good and bad thing). Functions are most useful for invoking actions on the consequence ("then") part of a rule, especially if that particular action is used over and over (perhaps with only differing parameters for each rule - for example the contents of an email message).

A typical function declaration looks like:

function String hello(String name) {
    return "Hello "+name+"!";
}

Note that the "function" keyword is used, even though its not really part of java. Parameters to the function are just like a normal method (and you don't have to have parameters if they are not needed). Return type is just like a normal method.

An alternative to the use of a function, could be to use a static method in a helper class: Foo.hello(). Drools 4.0 supports the use of function imports, so all you would need to do is:

import function my.package.Foo.hello

In both cases above, to use the function, just call it by its name in the consequence or inside a semantic code block. Example:

rule "using a static function"
when 
    eval( true )
then
    System.out.println( hello( "Bob" ) );
end