Language Enhancements in ColdFusion Splendor – Promoting built-in CF function to first class

A while ago I started a series of blog posts on Language Enhancements in ColdFusion Splendor and today, taking it forward, I am going to write about built-in ColdFusion functions being promoted to first class objects.

A first class object is the one which could be passed as an argument to a function call, assigned to a variable or returned as a result of a function invocation. So by promoting built-in functions to first class objects, you will be able to treat ColdFusion functions (structInsert, arrayLen, listFind) as objects and hence you can:

  • Pass them as arguments to a function call
  • Assign them to variables 
  • Return them as a result of a function invocation

Here is a very simple example showing how you can pass built-in functions as an argument:

 <cfscript>
	function convertCaseForArray(Array array, function convertor)
	{
		for (var i=1; i <= arrayLen(array); i++){
        	array[i] = convertor(array[i]);
                }
		return array;
	}
       
     // lcase built-in function is being passed as callback.
	resultantArray = convertCaseForArray(['One', 'Two','Three'],  lcase);	
	writedump(resultantArray);
</cfscript>

In the above example, lcase built-in function is directly being passed as an argument to convertCaseForArray, which was not allowed till ColdFusion10. Now, let’s see an example where the lcase and ucase built-in functions are being returned from the getConvertFunc function based on the type:

<cfscript>
	function convertCaseArray(Array array, String caseTo)
	{
		caseConvertFunc = getConvertFunc(caseTo);
		for (var i=1; i <= arrayLen(array); i++){
        	array[i] = caseConvertFunc(array[i]);
    	}
		return array;
	}
	
	function getConvertFunc(String caseType)
	{
	  if(caseType == 'lower')
	  	return lcase;
	   else
                return ucase;
	}
	
	resultantArray_lower = convertCaseArray(['One', 'Two','Three'], "lower");
	resultantArray_upper = convertCaseArray(['One', 'Two','Three'], "upper");
	
	writedump(resultantArray_lower);
	writedump(resultantArray_upper);

</cfscript>


In the above example, getConvertFunc returns the convertor for the right case. 

Stay tuned for more posts on language enhancements!

Leave a Reply

Your email address will not be published. Required fields are marked *