To scope or not to Scope that is the question.

One of the biggest problems, or should I say one of the of the most common questions I see is that isDefined('somevar') used to work in in ColdFusion 5 or it used to work in CFMX 6.1.

Since upgrading it no longer works!

</more>

Well to be point blank, ColdFusion has and will always work on scoped variables. If you refuse to scope your variables, and you are the one who ends up complaining that since upgrading your application no longer works.

Who do you have to blame, is it yourself, or is the programmer you took over from?

Either way, you must always scope the variable you wish to read / write and why is that? It is because the same variable could exist as a function, or it could exist in another scope that is read prior to the one you intended to have been read.

So the number one rule!!! Always scope your variables.



  • Ben Nadel's Gravatar Word up! Scoping is key! So is the structKeyExists() method.
    # Posted By Ben Nadel | 11/23/09 10:15 AM
  • Henry Ho's Gravatar As much as I want to scope all the vars, the Local scope makes the code much more unreadable.

    for (local.index = 1; local.index <= arrayLen(items); local.index++) {}

    compare to...

    for (local.index = 1; index <= arrayLen(items); index++) {}
    # Posted By Henry Ho | 11/23/09 11:08 AM
  • Andrew Scott's Gravatar @Henry - I have to say apart from the fact that you guarantee pulling up the right variable, scoping actual makes it easier to read. Local scope or not, prior to coldfusion 9, you would have gotten into the habbit if you followed convention, or best practice to use it as you described in your first example anyway.
    # Posted By Andrew Scott | 11/23/09 11:22 AM