coldfusionapplication.cfc

Do variables inside Application.cfc functions need scoping?


Question for the crowd. We are very strict on our team about scoping local variables inside functions in our CFC's. Recently though the question of scoping variables inside Application.cfc came up. Are unscoped variables in functions like onRequestStart() at the same risk for being accessed by other sessions running concurrently as we know that local variables in functions in other components are? Or are they somehow treated differently because of the nature of the functions in Application.cfc?


Solution

  • Your question borders on two entirely separate questions (both of which are important to clarify and address). These two questions are:

    1. Should I scope my variables correctly when referring to them (ie. APPLICATION.settings vs. SESSION.settings).

    The short answer to this is: Yes. It makes for cleaner, more readable / managable code, and prevents variable scope clashes that you may encounter later when variable names are re-used.

    If you create APPLICATION.settings and SESSION.settings, but attempt to refer to them without scope (ie. <cfset myvar = settings />), you're going to have variable clash issues, as they'll be poured into VARIABLES by default--since neither APPLICATION nor SESSION are examined to resolve scope ambiguity.

    The second question is:

    1. Should I be worried about variables that are accessed in Application.cfc that could be potentially be shared by multiple users in a concurrent environment?

    The short answer to this is: Yes. You should know & understand the ramifications of how your shared variables are accessed, and <CFLOCK> them where appropriate.

    Unfortunately, exactly when and where you lock your shared variables is often never clarified to the CF community, so let me sum it up:

    1. onApplicationStart() single-threads access to the APPLICATION scope. You do not need to lock APPLICATION vars that are read/written within this method.
    2. onSessionStart() single-threads access to the SESSION scope. Same answer as before.
    3. If you provide any kind of mechanism that accesses SESSION or APPLICATION from within the onRequestStart() method--or any other template afterwards (such as a URL reload parameter that directly calls onApplicationStart() )--all bets are off--you must now properly handle the locking of your shared variable reads and writes.