I was reading an article on The Server Side which compares the possible syntax for three proposals that would introduce closures into Java. The syntax is mostly awful but, again, one of the problems was the lack of decent examples. One of the comments mentioned transaction wrapping and that seemed to be such a good example that would resonate with ColdFusion developers that I thought I'd show it sketched out here:
<cffunction name="withTransaction">
<cfargument name="block" />
<p>Begin Transaction!</p>
<cftransaction>
<cfset arguments.block.call() />
</cftransaction>
<p>End Transaction!</p>
</cffunction>
<cffunction name="dbCode">
<p>I'm a database operation!</p>
</cffunction>
<cfset operation = cf.new(dbCode) />
<p>Naked operation:</p>
<cfset operation.call() />
<p>Transacted operation:</p>
<cfset withTransaction( operation ) />
This produces the following output:
I'm a database operation!
Transacted operation:
Begin Transaction!
I'm a database operation!
End Transaction!
The example doesn't show any bindings of variables but that would be where the real power comes in.
Does that help show where closures can be useful?
Someone might also think of it like what a dynamic cfinclude achieves for you in a template: You can specify the surrounding code while leaving the inner code for someone else to specify. That probably just muddied the water though. =)
I could bind a data source variable to the dbCode closure, both independent of the original function and of the (later) execution context. That's pretty powerful.
After reading the above, I threw this together:
http://www.bennadel.com/index.cfm?dax=blog:585.view
I think it's neat, but again, very hacky. When you have a few minutes, if you could take a peak and let me know if you have stuff built into your Closure stuff that could handle this much more elegantly.
If you don't have time, that's cool, this stuff is FAR from time-sensitive :)
Closures are something that make a lot of sense once you "get it" but make almost no sense until then... :)
The call for folks with both Ruby and ColdFusion experience produced the information I was looking for and it was passed on to the folks who needed it...


