User Guide

Table Of Contents
178 Chapter 9: Writing and Calling User-Defined Functions
Calling user-defined functions
You can call a function anywhere that you can use an expression, including in number signs (#) in
a
cfoutput tag, in a CFScript, or in a tag attribute value. One function can call another function,
and you can use a function as an argument to another function.
You can call a UDF in two ways:
With unnamed, positional arguments, as you would call a built-in function
With named arguments, as you would use attributes in a tag
You can use either technique for any function. However, if you use named arguments, you must
use the same argument names to call the function as you use to define the function. You cannot
call a function with a mixture of named and unnamed arguments.
One example of a user-defined function is a TotalInterest function that calculates loan payments
based on a principal amount, annual percentage, and loan duration in months. (For this
functions definition, see A user-defined function example” on page 192). You might call the
function without argument names on a forms action page, as follows:
<cfoutput>
Interest: #TotalInterest(Form.Principal, Form.Percent, Form.Months)#
</cfoutput>
You might call the function with argument names, as follows:
<cfoutput>
Interest: #TotalInterest(principal=Form.Principal, annualPercent=Form.Percent,
months=Form.Months)#
</cfoutput>
Working with arguments and variables in functions
Good argument naming practice
An argument’s name should represent its use. For example, the following code is unlikely to result
in confusion:
<cfscript>
function SumN(Addend1,Addend2)
{ return Addend1 + Addend2; }
</cfscript>
<cfset x = 10>
<cfset y = 12>
<cfoutput>#SumN(x,y)#</cfoutput>
The following, similar code is more likely to result in programming errors:
<cfscript>
function SumN(x,y)
{ return x + y; }
</cfscript>
<cfset x = 10>
<cfset y = 12>
<cfoutput>#SumN(x,y)#<cfoutput>