A valid use for the Evaluate() Function?
In the comments to my recent Rookie Mistakes post, Paul mentions that he is using Evaluate() to get the value of variables stored in a database. In this particular case, he's not storing the variable values in the DB, he's storing the actual variable names and then using Evaluate() to get their values via CF. To be specific he's storing a formula in the DB, and then using Evaluate() to perform the calculation and get the values.
Here's an example of Paul's situation:<cfset variables.var1 = 2>
<cfset variables.var2 = 9>
<cfset variables.var3 = 3>
<!--- This is the record that would be stored in the DB --->
<cfset variables.var4 = "(variables.var1 * variables.var2) / variables.var3">
<!--- lets fake a DB call. --->
<cfset variables.myQry = QueryNew("varString","VarChar")>
<cfset QueryAddRow(variables.myQry)>
<cfset QuerySetCell(variables.myQry, "varString", variables.var4, 1)>
<!--- Dump our query. --->
<cfdump var="#variables.myQry#">
The result of the dump would be:
#variables.myQry.varString#<br />
#Evaluate(variables.myQry.varString)#<br />
</cfoutput>
6
As you can see, outputting the variables normally just outputs the string stored in the DB, while the Evaluate() function translates the variables into their actual values, "(2 * 9) / 3", and then performs the calculation with no problem. Also if we try to do this using array syntax instead of Evaluate(), we still get the literal string that was stored in the DB.
#variables.myQry["varString"][variables.myQry.CurrentRow]#<br />
</cfoutput>
I played around with different variations of the output, and so far I have not been able to find a way to do this without using Evaluate(). I even spent some time trying to uncover what Java was doing under the hood with Evaluate(). In the end, I came up empty handed. My gut tells me that even if we went the Java route, it would wind up being more code and more cumbersome than just wrapping the variables in Evaluate().
So, my conclusion is this: This is a good use for Evaluate(). This is one of the rare cases when using Evaluate() is the right (only?) way to accomplish the desired results. If there's anyone out there that knows how to accomplish this without using Evaluate(), or a ton of extra coding, I would love to see it!


This is very true. My general dislike of Evaluate() is not a performance issue, but rather that I always felt it represented a misunderstanding of how variables could be accessed in ColdFusion. But, that's just a personal issue :)
When I can, I prefer to use a non-Evaluate() methodology. But, sometimes, as in this case, Evaluate() is the right choice.