Share this page to your:
Mastodon

This one is about how to add external functions to Madura rules. First, let’s look at a rule with a built in function:

formula: Customer “sum”  
 {  
 totalAmount = sum(invoices.amount);  
 }

This shows a simple formula rule which uses the internal function named sum(). Sum() in this case adds up all invoices attached to the customer object. The field on the invoice it uses is the amount field. There is another field, named totalAmount, that stores the sum.
Remember that if a new invoice is attached, an old one is removed or the amount on any invoice is changed this rule will fire and work out a new value for totalAmount.
We have a good selection of built in functions, things that manage dates, number conversions and lists. Sum() is an example of a list function. But what if you have your own idea for a function, can you write your own?
Well,of course, but there are some simple rules to observe so that the engine can use it. Here is an example of a user-written function:

public class SampleExternalFunctions {  

    @Function  
    public static String regex(String source, String pattern) {  
        return “yes, that’s okay”;  
    }  
    @Function  
    public static Number combine(Number a, Number b){  
        return a.doubleValue() + b.doubleValue();  
    }
}

The example shows two functions. Neither of them are very impressive in terms of what they do, but that is not the point here. The functions are both static functions and they both have the @Function annotation. That’s about all you need to remember. The class must go on the classpath of your application and also on the rules generator dependencies.
The arguments you pass to a function should be as neutral as possible to cater for all cases. So use Number rather than Long or Float. String and Date are fine.

Previous Post Next Post