User Guide

Table Of Contents
188 Chapter 9: Writing and Calling User-Defined Functions
Consider the following mechanisms for providing status information:
Use the return value to indicate the function status only. The return value can be a Boolean
success/failure indicator. The return value can also be a status code, for example where 1
indicates success, and various failure types are assigned known numbers. With this method, the
function must set a variable in the caller to the value of a successful result.
Set a status variable that is available to the caller (not the return variable) to indicate success or
failure and any information about the failure. With this method, the function can return the
result directly to the caller. In this method, the function should use only the return value and
structure arguments to pass the status back to the caller.
Each of these methods can have variants, and each has advantages and disadvantages. The
technique that you use should depend on the type of function, the application in which you use
it, and your coding style.
The following example, which modifies the function used in A user-defined function example”
on page 192, uses one version of the status variable method. It provides two forms of error
information:
It returns -1, instead of an interest value, if it encounters an error. This value can serve as an
error indicator because you never pay negative interest on a loan.
It also writes an error message to a structure that contains an error description variable. Because
the message is in a structure, it is available to both the calling page and the function.
The TotalInterest function
After changes to handle errors, the
TotalInterest function looks like the following. Code that is
changed from the example in A user-defined function example” on page 192 is in bold.
<cfscript>
function TotalInterest(principal, annualPercent, months, status) {
Var years = 0;
Var interestRate = 0;
Var totalInterest = 0;
principal = trim(principal);
principal = REReplace(principal,"[\$,]","","ALL");
annualPercent = Replace(annualPercent,"%","","ALL");
if ((principal LE 0) OR (annualPercent LE 0) OR (months LE 0)) {
Status.errorMsg = "All values must be greater than 0";
Return -1;
}
interestRate = annualPercent / 100;
years = months / 12;
totalInterest = principal*(((1+ interestRate)^years)-1);
Return DollarFormat(totalInterest);
}
</cfscript>