Scoping Makes Me And You Think Less

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.

Comments

New Comment