O'Reilly logo

Programming ColdFusion MX, 2nd Edition by Rob Brooks-Bilson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Advanced Topics

There are several advanced UDF topics worth covering here, including recursion, error and exception handling, and assigning UDFs to other variable scopes. Each of these topics covers techniques that you can use to maximize the benefit of using UDFs in your applications.

Recursion

As I mentioned in the beginning of the chapter, UDFs can be called recursively. This means that a UDF can call itself until a specific condition is met. Before you start creating recursive UDFs, there are a few things you should be aware of. First, too much recursion can be a bad thing. Recursion is both processor- and memory-intensive so recursively calling a UDF too many times has the potential to drain your server’s system resources to the point where it crashes the server. The ColdFusion engineering team recommends limiting recursive calls to fewer than 800 levels. If you have a situation where you know your recursive function call has the potential to exceed 800 levels, consider using a loop instead.

Here’s a classic example that uses recursion to calculate the factorial for a given number. The factorial for a positive integer is defined as the product of all of the positive integers between 1 and n. So, 5! equals 1*2*3*4*5. Written as a tag-based UDF, it looks something like this:

<cffunction name="Factorial"> <cfargument name="Integer" type="Numeric" required="Yes"> <cfif Arguments.Integer le 1> <cfreturn 1> <cfelse> <cfreturn Integer * Factorial(Arguments.Integer-1)> </cfif> </cffunction> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required