Scoping Makes Me And You Think Less

Posted Jun 14, 2009

When I'm programming in Coldfusion I don't want to have to think. To help me not to think much, I make an effort to scope out every variable.

When I go into a piece of code, I want to know whether the variable I'm looking at came from a query, form, argument or the various other sources a variable could come from. Otherwise I look at an unscoped variable and the first thought I have is where the !@#$%^ did this piece of code come from? Did it come from a query I see in a cfloop. Or is it an attribute passed from a calling script.

Probably the only exception I don't explicitly scope is for variables local to the script, unless I am using a CFC. If the variable is supposed to be a private variables, then I put “variables”. in front of it. I only wish there was something for var, but maybe I'm going overboard with that request.

Another reason to explicitly scope your variables is to prevent declaring a variable with the same name under 2 or more different scopes. Don't forget that Coldfusion has an order of precedence with respect to scope. You might have a variable with the name “id” coming from a query and another one coming from attributes. Which one are you accessing when you use #id#? Well if you memorized the scoping precedence from the Coldfusion documentation, you are probably ok. But even if you did memorize it, what if this isn't your code? Then you have to go through the script, hopefully it's not that big, and find everywhere id is declared.

Here's a the order of precedence Coldfusion gives in case your forgot. Honestly, I forget myself even though I'm sure I got this right on the CF Certification exam years ago:

Local variables
  1. cfquery
  2. CGI
  3. File
  4. URL
  5. Form
  6. Cookie
  7. Client
These are some other variables that should definitely be scoped:
  1. Server
  2. Application
  3. Session
  4. Request
  5. Attributes
  6. Error
If you're using CFC's or functions, the order changes a bit to this:
  1. Function local
  2. Arguments
  3. .Variables
  4. CGI
  5. CFFile
  6. URL
  7. Form
  8. Cookie
  9. Client

I couldn't find anything on the this scope. I should test it out one day and update.

Discussions

Comments are currently turned off

Latest Discussions

  • Carlos: Thank you!
    May 16, 2014 | Replies (0)
  • Jessica: Great info, thanks!
    May 15, 2014 | Replies (1)
  • Walter: Thanks, you totally saved me a bunch of searching around just now. I was setting up a percona xtradb...
    Feb 25, 2014 | Replies (0)
  • Avi: I've found the reason of the problem in my case. It's a bug as described here :http://bugs.mysql.com/bug.php?id=68892Shortly:...
    Dec 12, 2013 | Replies (0)
  • Avi: I've also met that behavior twice on 5.6.12 slaves. However, i didn't find the root cause of that....
    Dec 12, 2013 | Replies (0)