Monday, February 28, 2011

ColdFusion musings on variable scope

Well I've come across the use of using local to reference all local variables in a function and some phobia to use var for declaring local function variables. I must admit I find this weird. I'm an avid fan of using var but that probably comes from my development in ActionScript and other languages I've developed in such as Java, C/C++. To me the phobia comes directly from the dreaded "memory leak" where you have the variable scope referenced instead of the scope relative to the function (local). This seems like a flaw in ColdFusion that a variable which is not scoped can appear to be causing the developer to have memory headaches. But to me I think developers should be more wary of what they are coding. The use of the local structure just seems like a lame hack which bloats the amount of code you write. ColdFusion is on it's own when comes having such a verbose way of referencing local scope variables. So really this is an issue of scope and a better solution would be to make it that you have to reference variables not in the local scope explicitly instead of the of reverse... well that being said people also just go and ahead an explicitly reference all variables which means a lot of typing. I don't care if you have intelli sense it means more typing no matter what.

So I do hope in the next version of ColdFusion they solve this problem because it makes code look ugly and longer to write... two things which ColdFusion is suppose to be working against. And yes I love my but you need a hand.

My feelings towards cfscript are similar to Ben Forta's. Read his post on I Am Not A Fan Of CFSCRIPT


doug s said...

Just thought I would mention using var isn't about memory leaks, its about data leaking across functions in a cfc. An easy example is to create a cfc with two functions and no 'var' on any variables. in function a run a random query. in the second function, check the value of queryname.recordcount. then create a test page where you create the cfc and call function a then function b on the same instance of the cfc. instead of an undefined error, you will get the record count from that other function.

this causes really hard to diagnose/reproduce errors (perhaps the 'i' counter from one function is overwriting another loop with the same counter name )

so in my opinion, if someone wants to var scope the 'local' struct as a way to make sure variables are not missed and unscoped, it beats the alternative...

Ross Phillips said...

@Doug yep I agree with your statement. Can't say I like the term "memory leak" though I've found CF developers using the term to describe exactly what you have described. But thinking about it now I should have left the term out.

I suppose my intended sentiment was that the excessive use of "local" is a syntax problem we should not need to deal with as CF developers in general.