Tuesday, July 22, 2008

CFC's - Arguments Scope Vs. local VAR

This morning I had some trouble in one of my CFC's. I thought I was a seasoned ColdFusion developer, but this morning I felt like a newbie. I learned that hard way about VAR'ing local variables inside CFC's. This is separate from SCOPING variables and this is only done inside functions (which make up CFCs).

I was always a little fuzzy about the "variables" scope being visible in the same component between CFC's. I had read it and knew it, but never had it crossed my path as being a problem. Occasionally, in a rare circumstance where I had code looping over a CFC I would get odd results. On a reload it would not repeat the problem. They were so rare in fact, and never cause errors, that I never took the time to investigate the occasional strange display issue that was difficult to repeat. I thought these were strange 'ghost' bugs. I digress.

So today I did my research. And, I cleaned up some of my CFC's so that there are no "Variables" scoped variables, only <cfset var myvarname = ""> initialized at the top of the CFC and below any <cfargument > tags. I found that I had been doing some of this:

<cffunction name="func_name" access="public" displayname="func_name" output="yes">
          <cfargument name="someID" type="numeric" required="No" default="0">
          <cfset arguments.loopCounter = 0>
          <cfloop ...

I tried to research the difference betwee the "Arguments" scope and the VAR scoping. I got no where. No one talks about it. They are both extremely local variables within the function, but they appear to be in separate scopes. I trusted this as I was cleaning up my CFC's and testing my code.

Then I ran into this:

<cffunction name="func_name" access="public" displayname="func_name" output="yes">
          <cfargument name="userID" type="numeric" required="No" default="0">
          <cfset arguments.userID = 0>


Error Occurred While Processing Request

Cannot declare local variable userID twice.

Local variables cannot have the same names as parameters or other local variables.
 


Now I know that the "Arguments" scope IS the local "VAR" scope. Hope that helps a few of you out there.

So this means that if you don't like the <cfset var someID = 0> you can use the real 'arguments' scope as <cfset arguments.someID = 0>.


If any java guru's out there can shed some light on any memory difference under the hood of the CFML engine between the local arguments scope and local var'ing, please do. I'm itching to know.