I'm embarrassed to admit that I haven't done much development with CFC's. Considering my background as a Java developer, there really is no excuse.
So I'm trying to make up for lost time. Almost all the development I'm doing these days involves CFC's. Many times I'm moving existing code in to new CFC's, but the benefits are great. Its the single most important feature in the language.
Of course, my CFC honeymoon came to a crash ending. I have a component that certain information on each link on the site. The data is stored in a database, but because there are many lookups for each page rendered, I didn't want to do a database lookup. Instead, I created a component that stores the data in a struct, keyed on the URL. The component is stored in the Application scope, so the data is pulled once, and the lookup happens in the component.
Each element in the struct is actually another struct with a bunch of information regarding that link. The function urlLookup first initializes the return variable called "info"
<cfset info = "">
then does the lookup
<cfif structKeyExists(urls, key)>
<cfset info = urls["#key#"]>
<cfset info.foundResult = true> <!--- flag this as a valid result --->
</cfif>
because I'm expecting a struct from this function, if no URL was found, I create a struct and set the foundResult to false
<cfif info is "">
<cfset info = StructNew()>
<cfset info.foundResult = false>
</cfif>
then return info
<cfreturn info>
Mysteriously, I kept getting errors "Element FOUNDRESULT is undefined in URLS". Can you spot the error? Remember, this object is in the application scope, so many requests are hitting it at once.
The problem is in this line
<cfset info = "">
the variable "info" is a global variable, not local to the function. If a second request enters the function before a previous request finishes, it re-initializes the global variable "info," which is then returned. FOUNDRESULT will not be found because the variable is an empty string!
The solution is a to add a little keyword "var," so the line of code looks like this
<cfset var info = "">
this makes the variable local to the function, so each call to the function creates a new variable local to that call. It is recommended that all variables, including query names, be initialized with the var keyword (referred to as "varing" your variables.)
Item of the Day: KWC Domo 10.061.033 - Kitchen Faucet from KWC