Coldfusion’s Evaluate()

by Pirate Gaspard on May 18th, 2010

Today I was going through an application turned over by a contractor and I began noticing that evaluate() was used frequently through out the code.

I thought by now we’d all know that using Coldfusion’s evaluate() function should be avoided. Evaluate() is a performance hit and is an indication of sloppy code. It may be possible that there are situations where it is unavoidable, but in my experience if you are considering to use evaluate() to solve a problem its a red flag that there is a better solution if you just think a little longer.

Structures

evaluate() example:

<cfloop from="1" to="10" index="i" >
     <cfset blah = evaluate("myStruct.myKey#i#") />
</cfloop>

With Structures it is easy to avoid using evaluate() as you can dynamically create the struct key such as:

<cfloop from="1" to="10" index="i" >
     <cfset blah = myStruct["thisKey" & i] />
</cfloop>

Queries

evaluate() example:

<cfset myfield = "blahblah" />
<cfloop quser="q" >
     <cfset blah = evaluate("q.#myfield#]") />
</cfloop>

Queries are not much different than structures. The trick is that you’ll need to explicitly define the current row. This is something that is normally implicit.

<cfset myfield = "blahblah" />
<cfloop quser="q" >
     <cfset blah = q[myfield][q.currentrow] />
</cfloop>

Function Calls

<cfset myvar = "FirstName" />
<cfset blah = evaluate("get#myvar#()") />

Dynamically declaring function calls is a neat trick. The example code is a very (very) basic generic getter function, perhaps utilized within onMissingMethod(). Given any string it will try to call a getter function for that property. There is no other syntax to create this call. But using evaluate() should be a red flag. When you get into a situation such as this you should really ask yourself why you are organizing your code this way.

Perhaps you could forgo building a named function for each property and restructure your generic getter function to work like this:

<cfset myvar = "FirstName" />
<cfset blah = get(myvar) />

or possibly even simpler as:

<cfset myvar = "FirstName" />
<cfset blah = variables[myvar] />

You should definitely be asking yourself why you would call a generic getter function if you built named getter functions. (Maybe you’ve made the methods private?) This is a simple example, but either way evaluate() is most often a sign of a larger coding problem.

Share
2 Comments
  1. Tom permalink

    Like you, I know to avoid using evaluate but I forget the syntax. I’ve been searching all over for the syntax when accessing data stored in a structure and looping over the output. I found your post (thank you google preview) and when I arrived, I found many other examples of syntaxes!

    Thanks!

  2. Great post! Like Tom, I know to avoid, but can never remember the darn syntax. Thank you!

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS