Tim Blair

Local (var) Scope Shortcut (27/12/2004)

Maybe it's just me, and I'm being really really slow, but only this week I've picked up on a nice little shortcut... We've all heard the lecture on var-ing all your local variables within a <cffunction> call, but sometimes the odd one slips through, and with memory cached components, stray, unscoped variables can cause all sorts of hassle!

As I said, the idea is simple, and I'm sure that a huge number of CF developers are already using it. Instead of var-scoping every single variable you've going to use within a function (and having the possibility of missing one or two in long functions etc), why not just create a single new "scope", which itself is var-scoped, to place all your variables in? All the existing scopes are effectively structures, so how about creating a structure to act as a local "scope"?

Now personally, having just thought about it, I don't see why this extra "scope" hasn't been added to CF from the start. It would make sense either to have the scope available at any point within a <cffunction>, or even using it as the default scope within functions, rather than the variables scope (in which case, all variables would be local scoped unless explicitly told otherwise).

Of course, this method doesn't automatically create the new scope for you, and doesn't mean that you'll never have variables that are not locally scoped (you'll still have to remember to put the local. before each variable), but I do think that it reduces the chances of variables left going unchecked.

Update (18/06/08): It looks like, after three-and-a-half-years, my shortcut has been made official! As of CF9, the local scope within functions will be implicitly defined. See the CFUNITED keynote, timestamped at 9:24AM, for that little bit of information.

Article Archive (September '03 – '05)