Custom Function Libraries

Estimated reading: 2 minutes 5 views

Introduction

The Wattyo Rule Engine support the creation of Custom Function Libraries. This enable to extend the rule engine with any kind of function / method that you need.

In order to extend the Engine you would need to create an APEX class that implements the CustomFunctionLibrary interface.

The Architecture

Each time the rule engine is invoked in a transaction it will check for all the Classes that implement the CustomFunctionLibrary interface, both Out-of-the-box and Custom ones.

For each of them, it will call the register method, which would return all the available functions in that Library and store them in a Functions Map.

Once all Libraries have been processed the engine will have a map with all the different functions and it’s corresponding CustomFunctionLibrary implementation.

Note that different functions can be related to the same implementation.

Later, when a function must be evaluated, the engine will check if the function is registered and execute it, otherwise it will throw an Exception.

register()

This method must return a List with all the different functions supported by the Library.

evaluateFunction(String functionName, List params, Map<String, Object> vars);

It’s in charge of processing the specified formula with the received parameters and variables.

Implementation Example

public with sharing class CommonFormulasLibrary implements CustomFunctionLibrary {

    public static List<String> register(){
        return new String[]{'max'};
    }

    public static Object evaluateFunction(String formulaName, List<FormulaEngine.Result> params, Map<String, Object> vars){
        if(formulaName == 'max'){
          return  evaluateMax(params, vars);
        }
        return null;
    }

    private static Object evaluateMax(List<FormulaEngine.Result> params,  Map<String, Object> vars){
        Object max = null;
        FormulaEngine.DATA_TYPE maxType = null;

        for(FormulaEngine.Result param: params){    
            if(maxType == null){
                maxType =param.dataType;
            } else if (maxType != param.dataType){
                throw new FormulaEngine.EvaluationException(String.format('Max function must be applied on same data types: {0} and {1} are different.', new String[]{''+maxType, ''+param.dataType}));
            }

            if(max == null){
                max = param.value;
            } else if(maxType == FormulaEngine.DATA_TYPE.NUM){
                max = (Double)max > (Double) param.value ? max :  param.value;
            } else if (maxType == FormulaEngine.DATA_TYPE.TEXT){
                max = (String)max > (String) param.value ? max :  param.value;
            }

        }
        return max;
    }

}

Leave a Comment

       
Euphoria, forever till the end of times

Euphoria

Share this Doc

Custom Function Libraries

Or copy link

CONTENTS