CF9 Scoped functions named arguments example
June 3, 2010 1 Comment

ColdFusion
Back in August last year, I did a post titled “CF9: Named arguments for scoped functions“. It boiled down to the fact that in earlier versions of ColdFusion, if you referenced a user defined function (not talking about CFC’s here) by the scope it lives in, you wouldn’t be able to use named arguments when calling it. So bob(top = ‘bottom’) was fine, variables.bob(top = ‘bottom’) would throw an error. This was fixed for the final release of CF9, woohoo.
So having been the one to pester Adobe about it originally, I thought I’d better come up with an example of why fixing it was a good thing. In the code that follows I have two functions. One of them is a simple function that adds a random number to a value, based on the key. The other simple walks an array, executing a callback function on each item.
<cfscript>
function randomByKey(required numeric key, required string value) {
Randomize(arguments.key);
return arguments.value & ' ' & RandRange(10000, 99999);
}
function arrayWalk(required array array, required any callback) {
local.len = ArrayLen(arguments.array);
for (local.i = 1; local.i Lte local.len; local.i++) {
arguments.array[local.i] = arguments.callback(
key = local.i,
value = arguments.array[local.i]
);
}
return arguments.array;
}
testArray = ['bob', 'bob', 'bill', 'bert', 'barney'];
WriteDump(arrayWalk(testArray, randomByKey));
</cfscript>
The important part of the code is within the “arrayWalk” function, where it references arguments.callback. You could easily just use ordered parameters for calling the function, or remove the “arguments.” from the callback and it’d still have worked. But it wouldn’t have been as readable without the named parameters and unless you want to invoke the wrath of VarScoper you should always scope your variables in a function.
I’d be really interested if anyone thinks this will come in useful to them or have already been using named parameters for scoped functions in CF9.


Found something extremely useful and want to thank me with more than just words?
Pingback: ColdFusion 9 Tutorials and Resources | My Blog