Recursive Functions - For the AL Developer
Recursive functions can be a powerful asset in the developer toolbox, but in Dynamics BC the only example I know of is in manufacturing, and that's complicated to follow. Below I have a simpler example.
The scenario is the following. Our customer has contractually committed to put monthly limits on what they would invoice their customer. The requirement is to have the ability to setup multiple billing limits for a sales order and all of the limits are active simultaneously. The client uses the Jobs module so the limits are setup per Job. For example, assume that we have a Job, J100R with many Job tasks, here are the limits the user wants to setup ...
Job cannot bill more than $50,000 &
Task T0001 cannot bill more than $9,250 &
Resource R100 cannot bill more than $15,000
What's interesting about this requirement is that all three can be valid for a sales line. If resource R100 has time for task T0001, you have to test all three limits. The code below shows the essence of how the recursive function is used.
limits.setfilter("Job No.",'%1 ','J100R'); limits.setfilter("Job Task No.",'%1 | %2', 'T0001', '' ); limits.setfilter("Resource No.",'%1 | %2', 'R100', '' ); limitReached := CheckLimits(limits); if not limitReached then addLineToSalesOrder(sLine); Procedure CheckLimits(var limitsRec: record LimitsTable; sline: record "Sales Line") decimal var reachedLimit: boolean; limitsLocal: record LimitsTable; begin limitsLocal := limitsRec; while limitsRec.next<>0 do reachedLimit := CheckLimits(LimitsRec, sline); //your implementation logic here ... exit(reachedLimit); end;
The limits table in our example returns three records. The CheckLimits() function calls itself for each record returned. Since the record is being passed by reference, the while loop will end once all three records have been retrieved. When the last record is retrieved, code below the while statement will execute. The local variable limitsLocal can be used to execute the appropriate business logic for the instance of CheckLimits() on the stack. The return value will bubble up the result until control returns back to the main body of your code.
A typical use of recursive methods is to go through a parent child hierarchy but in ERP you don't see that much.. The manufacturing BOM with sub-assembly is a good area for a recursive function.
Hope this gives you some ideas for your next AL project.