Friday, May 4, 2012

IsDefined invalid variable name error

It is widely known that StructKeyExists is faster than IsDefined since IsDefined still searches all scopes for the variable until it finds it, whereas StructKeyExists explicitly defines the scope to search.

Sean Corfield also explains why IsDefined can be confusing and arguably buggy.

I ran into another buggy situation at work this week where we were checking for the existence of a variable that may or may not have a hyphen in the variable name. I know it's bad practice to have a hyphen in a variable name, but this was inherited code and the variable name was set dynamically at runtime based off a varchar ID (that's another story).

The code below will blow up when using IsDefined if the variable does not exist because you cannot have hyphens in a ColdFusion variable name. The interesting thing is that it works if the variable does exist. Of course, StructKeyExists works as expected even with the hyphen.