0

Using a "scope" for var in functions

ColdFusion

I like using a "scope" for vars and so create a structure called private at the top of most functions:

Why create a structure to hold var variables?

  1. It seems more natural with how CF works. Its always better to scope variables in CF, yet, along comes one scope var where we are not meant to? This way all my vars are prefixed with private in the same way other scopes are form, arguments, requests, etc.
  2. No need to define all variables at the top of a function. Say I have a loop in the middle of a function, I can now do cfloop index="private.i" and know that I have not accidentally created something in the variables scope. I just find this easier than going to the top of the function and setting a new var and from experience when something is easier I am more likely to do it.

When not to do this?

If a function is simply returning a query (or using one or two var variables) there is no point in creating a structure instead do this:

Is it necessary to use the var scope?

Yes, yes, yes. For clarification read this from Ray Camden. And a testimonial of why.

Is there a performance hit with using a structure?

This came up in the comments discussion of a post on Ray Camden's blog yesterday. The answer? Not really. I did a comparison of two functions, one that set a structure called private and set one variable into it and another that just set a var variable. I then created the object and called the function 500 times. First the results and then the code:

Testing is on my PowerBook G4, at work on an iMac with dual core, the times where about a tenth.

Is it necessary to use private?

Not at all, in fact there are some who strongly caution against this (see Todd Sharp's comment in this post which is also where I heard about the idea of using a structure for var).  Some suggest using local, though, this is a reserved word in query-of-queries, really anything can work.  You can even use var but that just seems likely to confuse anyone else who works on your code in the future.

tags:
ColdFusion
Christopher Vigliotti said:
 
I've been doing this for a few months now and have to say that it's super helpful. Having said that, some may consider it bad form to not declare your variables at the top of a function.
 
posted 677 days ago
Add Comment Reply to: this comment OR this thread
 
Christopher Vigliotti said:
 
Quick follow-up, you'll have to use brackets as outlined in this post >> http://www.bennadel.com/blog/94-LOCAL-Variables-Sc...
 
posted 607 days ago
Add Comment Reply to: this comment OR this thread
 

Search

Twitter
You should follow me on Twitter here
About Me
I am a 34-year old Web Developer specializing in ColdFusion. I live and work in downtown Washington, DC with my wife and two daughters. Read more About Me

2007 CFeMmy Best Newcommer winner
As voted on by fellow CF Bloggers.
CFinNC - Carolina ColdFusion / Flex / Air Conference - Oct 17-18, 2009