User Defined Functions in ColdFusion

User defined functions allow developers to keep frequently used pieces of code together in reusable units. For example, you may often find yourself checking the size of a particular file or counting the number of records in a database table. You might find that you need to find out if a string is upper or lowercase, or convert a string to an array of single characters.

Whatever your need, user defined functions (UDFs) can help you accomplish your goal. In this article, I’ll show you how to create user defined functions using cfscript so that your function is compatible with both ColdFusion 5 and ColdFusion MX.

cfscript Functions

cfscript has been around since at least version 4.01. It basically allows a developer to write ColdFusion code in C-style syntax. There are limitations to cfscript, though. For example, you can’t call ColdFusion tags from within cfscript. You have to use available functions. cfscript has been proven to offer some performance benefits over the use of tags in some situations, and it often results in your using less code than you may otherwise need. In addition, in ColdFusion 5 you can create your own functions only by using cfscript. It’s in this context that we’ll use cfscript to build our own functions that are compatible all the way back to version 5.

For our first examples, we’ll use a couple of functions I posted in the ColdFusion blog back in April, which allow us to figure out if a character is uppercase or lowercase. We’ll then add a couple of functions to increase the script’s capabilities in ways that may be useful in the future.

The Uppercase Function

To start, let’s build a function to tell us if a character is uppercase. We’ll then build one to tell us if a character is lowercase. Here’s the code for the function:

<cfscript> 
  function isUpperCase(character) {
     if (Asc(character) gte 65 and Asc(character) lte 90)
        return true;
     return false;
  }
</cfscript>

First, we open our cfscript block. Next, we create a function using the function keyword. We give it a name and then specify, in parentheses, the parameters that it takes. Does this look familiar to you? If you’ve ever worked with JavaScript, it should. This is exactly how a JavaScript function is declared (except for the cfscript block). There are a few things to note about ColdFusion UDFs, though:

  • You cannot overload or re-declare a function. Once you create it, you cannot create another function of the same name.
  • You cannot specify default values for parameters in a ColdFusion UDF.
  • You cannot specify optional parameters for a UDF. Every parameter you use in the declaration must be passed in the function call.

Now that I’ve told you what you cannot do with UDFs, here’s something you can do: you can specify parameters that are not declared. For example, I have only declared one parameter for the function above, but I can pass in three, or four, or more parameters. So, a normal function call would look like this:

<cfoutput> 
  #isUpperCase("A")#
</cfoutput>

This would display the value "true". Note that if I passed in the string "Aaaa" it would still be true, because the Asc function uses the first character of the string passed in and ignores the rest.

However, if I call it with a couple of extra parameters, it will still work:

<cfoutput> 
  #isUpperCase("A", "a", "b")#
</cfoutput>

This will still display "true". It doesn’t use those additional parameters. But what if we want to use the additional parameters passed into the function? How do we get to them, you ask? It’s really quite simple. Inside the function, we have an array called "arguments". So, if we want to use the second and third parameters, we can simply access them via this array.

<cfscript> 
  function argsTest() {
     for (i = 1; i lte ArrayLen(arguments); i = i + 1) {
        WriteOutput(arguments[i] & "<br />");
     }
  }
</cfscript>

This will write out all the arguments that we pass in. We call the function this way:

<cfset a = argsTest("I", "am", "ready", "to", "code")>

Using the above code, we’ll get each of those arguments printed on a separate line. Notice a few things about our function here:

  • We use "lte" for our comparison. This is because, even though it’s a different syntax, it is still ColdFusion. We must use normal CF operators for comparisons and logic.
  • We use i = i + 1 instead of i++. This is because, again, we’re still using ColdFusion, which does not support the ++ operator.
  • We use the WriteOutput() function to display variables and other information to the page. This is sort of like using document.write() in a JavaScript function.
  • As in our uppercase function, note that we can use normal ColdFusion functions, such as Asc(), Chr(), Len(), ArrayLen(), ArrayNew(), etc., as well.
  • Notice the return statement in our uppercase function. In this function, we return a simple Boolean, which can then be assigned to any variable we choose. But, we can also return complex values, such as structs and arrays. We’ll see this in just a minute.
The Lowercase Function

Now, let’s code our lowercase function. The ASCII values for our lowercase characters are 97 through 122, so we’ll basically copy and paste the uppercase function and modify those two values.

<cfscript> 
  function isLowerCase(character) {
     if (Asc(character) lte 97 and Asc(character) gte 122)
        return true;
     return false;
  }
</cfscript>

That will do for those functions. Now, let’s build a function to decide if it is upper or lower case, and alert us to that. We’ll return the value "upper", "lower", or "false" depending on the character passed.

<cfscript> 
  function isUpperOrLowerCase(character) {
     if (Asc(character) gte 65 and Asc(character) lte 90)
        return "upper";
     else if (Asc(character) gte 97 and Asc(character) lte 122)
        return "lower";
     return false;
  }
</cfscript>

We can use the function in this way:

<cfif not isUpperOrLowerCase("a")> 
  This is not a character.
<cfelseif isUpperOrLowerCase("a") eq "upper">
  This is an uppercase character.
<cfelse>
  This is a lowercase character.
</cfif>

This demonstrates the ability to return a data type other than a Boolean from a UDF. Now, let’s return something more complex: an array. We’ll create a function that will turn a string into an array of characters.

<cfscript> 
  function toCharacterArray(str) {
     var CharArray = ArrayNew(1);
     for (i = 1; i lte Len(str); i = i + 1) {
        CharArray[i] = Mid(str, i, 1);
     }
     return CharArray;
  }
</cfscript>

This accepts a string as an argument, creates a new, one-dimensional array, loops from 1 to the length of the string, and pulls out each character, stuffing it into the array at the current index, represented by the variable i. We then return the character array.

<cfset a = toCharacterArray('This is my array")> 
<cfdump var="#a#">

The script above displays a neat little table that shows every value in the array. It really is that easy to create user defined functions in ColdFusion. Now that you know how to create user-defined functions in ColdFusion using cfscript, here’s your assignment:

Go through a current project, or a Website that you’ve previously built in ColdFusion, and identify the pieces of that project that could be built into functions. It may be that you use the same functionality in several places, or that you could clean up your code and simplify it by removing it from the body of your templates and putting it into a template. Then, build your functions, store them in a single file (if there are not too many) and simply include them where you need them. You could also create a directory in your site called "udfs", or something like that, and put each function in a file of the same name. Then you simply include the functions you need.

If you want free user defined functions, you may want to look at CFLib – you’ll find tons of very handy functions there.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.