Say I have a very simple controller like so:
<cfcomponent extends="Controller">
<cffunction name="hello">
<cfset time = Now()>
</cffunction>
</cfcomponent>
In straight ColdFusion / Railo, I would be locally scoping all variables within this...but every wheels example I see does not.
This is probably going to earn me the dumbest question of the year award, but it was something I was thinking about, since nobody ever seems to demonstrate their Wheels code scoped correctly?
I would write it as follows:
<cfcomponent extends="Controller">
<cffunction name="hello">
<cfset local.time = Now()>
</cffunction>
</cfcomponent>
I am just not sure if Wheels perhaps does something to remedy this regardless, and that's why I see what I do everywhere...or is it just a case of bad programming?
Thanks! Mikey
Yes, you should be scoping it.
In your first example, you are (by not scoping) in most cases setting variables.time
, which is local to the component instance, not to the function - if this is intended as a function-local variable (i.e. local.time
) but is in the component's variable scope, and that component is shared/persisted, this may cause issues (though perhaps ones that only reveal themselves under heavy load).
If putting the variable in the variables scope is deliberate, it should still be explicitly scoped (as variables.time
) otherwise it may cause issues if used on a Railo server with the localmode setting enabled.
Due to a cfWheels design decision (see links in comments), putting variables in the variables scope is required to pass variables to the view, even though they may technically be local to the function/view. (The controller instance lives for a single request, avoiding the issues this normally entails.) As mentioned in the previous paragraph, the localmode setting (described below) means it is still recommended to explicitly scope when you are not in control of all servers the code will be deployed to.
Railo (since v1) has had an admin setting called "localmode" which defines whether assigning an unscoped variable will go to the local scope, rather than the component's variables scope - making explicit var/local scoping not required (if you know your code will only be run on Railo servers with that setting enabled).
Since that setting is off by default, and ColdFusion does not have such a setting, cross-engine-compatible code should always scope such variable assignments to avoid this being an issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With