Skip to content
March 21, 2006 / dshuck

VAR scoping using structures

At this stage in the game of ColdFusion, it is common knowledge why you must var-scope all variables in your methods in order to protect your data.  In case this is something new to you, say you set a variable named “myVar” in method A.  Say you had a method B and in it you had another “myVar” with a different purpose.   Unless you declare your variables like this: <cfset var myVar = “something” />  that data is shared between both methods and can be overwritten.

So typically when you have a method you var-scope all your private variables including queries or anything else like this:

<cffunction name=”a” output=”false” returntype=”void”>
<cfset var myVar = “” />
<cfset var qQuery = “” />

<….. then all your code …>
</cffunction>

One thing I have never been fond of is that once this is done there is effectively no visible difference in your code between variables that are var scoped and variables that aren’t.  For example, let’s say I var-scope mVarA and don’t var-scope myVarB.  When I access them in the method they visibly appear to be in the same scope… like this:

<cffunction name=”a” output=”false” returntype=”string”>
<cfset var myVarA = “” />
<cfset myVarB = “” />

<cfreturn myVarA & myVarB />
</cffunction>

Looking at this, there is no visible way to see which of those variables is var-scoped without looking at the top of your method to see what you have done.   Plus, as you add variables to your methods, that var-scoping area will grow and you can have a large section of protected declarations.  I have found a different way to approach this by var-scoping a structure named “private” at the top of my methods.  Then in my code I can simply use <cfset private.myVar = “” />.  For example, the code above would become:

<cffunction name=”a” output=”false” returntype=”string”>
<cfset var private = structnew() />

<cfset private.myVarA = “” />
<cfset myVarB = “” />

<cfreturn private.myVarA & myVarB />
</cffunction>

By doing this, I no longer have to go var-scope each individual variable, plus the code becomes far more obvious as to which variables exist in that “private” scope.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 591 other followers