The simplicity of ColdFusion 9 Part 1
Reduction is a key weapon in the battle against unnecessary complexity. The current version of Adobe ColdFusion provides a number of syntax and other improvements which allow developers to write less code than in earlier versions.
Here's the first in a series on some of my favourite code-reducing features.
Local scope
Pre-CF9 there was no explicit scope in which to put variables which should only be available inside a function. To create such "local" variables you needed to declare them at the top of the function with the var
keyword. A common practice was to declare a single structure called "local" which could then be used as a "pseudo-local" scope, allowing variables to be created anywhere.
<cffunction name="myFunction">
<cfscript>
var local = {};
local.x = 1
doSomethingTo( local.x );
local.y = 2 + local.x;
</cfscript>
</cffunction>
Useful though this technique was, it meant adding this line to the beginning of every single function.
CF9 introduced a built-in local scope for functions which you could reference with local.
without needing to declare it:
<cffunction name="myFunction">
<cfscript>
local.x = 1
doSomethingTo( local.x );
local.y = 2 + local.x;
</cfscript>
</cffunction>
Var
anywhere
While I prefer to explicitly scope most of my local variables by prefixing them with local.
, there are times where declaring them leads to cleaner code, such as with loops.
<cffunction name="myFunction">
<cfscript>
var i=1;
local.things = getAnArrayOfThings();
for( i=1; i LTE ArrayLen( local.things ); i++ ){
local.result &= local.things[ i ];
}
</cfscript>
</cffunction>
CF9 allows you to declare local variables anywhere, which means we can get rid of the declaration at the top and stick it directly in the loop, saving us a line and removing the disjunct between the variable's declaration and use.
<cffunction name="myFunction">
<cfscript>
local.things = getAnArrayOfThings();
for( var i=1; i LTE ArrayLen( local.things ); i++ ){
local.result &= local.things[ i ];
}
</cfscript>
</cffunction>
for/in
loops
A new enhancement in the 9.0.1 Updater is perhaps my top "pro-simplicity" feature as it not only reduces the quantity but can also improve the clarity of your code - another key aspect of simplicity. Taking the previous loop, we can remove the obfuscating iterating operators/syntax and make it much more readable:
<cffunction name="myFunction">
<cfscript>
local.things = getAnArrayOfThings();
for( var thisThing in local.things){
local.result &= thisThing;
}
</cfscript>
</cffunction>