The Dopefly Tech Blog

« The Dopefly Tech Blog Main page

Fun with Functions and CFCs VIII - Functions as Variables and Functional Programming

posted under category: ColdFusion on December 19, 2007 at 12:00 am by Nathan

CFML acts a lot like Javascript, really. In this series, I've been throwing around functions like they were candy. Indeed, ColdFusion and CFML let you do that. So let's have some fun with it.

function add(n1,n2) {return n1+n2;}
function subtract(n1,n2) {return n1-n2;}

function doSomethingWith2Numbers(thingToDo, n1,n2) { return thingToDo(n1,n2);}

writeOutput( doSomethingWith2Numbers( add, 5, 5) );
writeOutput( doSomethingWith2Numbers( subtract, 5, 5) );


Just the fact that you can is awesome.

The best benefit I can see right now for tossing around functions as arguments is for late-binding actions. You compile a handful of things to do, then execute them at the last possible moment. I like this approach for generating UI elements from OO systems in particular. We set a bunch of preferences, then, when you call render(), the system spits it out based on different code generation methods that were previously defined. That's one of my favorite things: instead of asking if a switch is on or off, just execute the method resting in a function reference.