When declaring variables in CF do you like :one: ...
# cfml-general
j
When declaring variables in CF do you like 1️⃣ var foo - or - 2️⃣ local.foo I've always preferred local.foo because I don't have to think about it - I know it's scoped regardless of where I see it in the code.
1️⃣ 10
a
var foo
and thereafter don't scope it. Your method code should not be so long that you lose track of whether a variable is correctly `var`ed or not. If it is... that's your problem. Not
local.foo
or
var foo
.
💯 1
☝🏻 1
r
As Adam said, although I do use
local.foo
when you have to declare a variable in a tag or function like...
Copy code
<cfquery name="local.myQuery" ...>
...but then reference it thereafter without the scope, like...
Copy code
<cfloop query="myQuery" ...>
v
Also another advantage of using local.foo is just in case you have to use
structKeyExists
.
Copy code
StructKeyExists(local,"foo")
It doesn't work with var scope so you will need to use
isdefined
z
Really?
a
We are mixing up notions here. There is no "var scope".
var
is a keyword that is used in a variable initialisation statement that puts the variable in the
local
scope. The scope in all cases discussed here is the
local
scope. Once a variable in the local scope is initialised, one can safely reference it without the scope: the scope with be inferred during code execution. Whilst CFML engines do that scope look-up thing, the
local
scope is the first one checked, so there is absolutely no harm in not being explicit about the scope, plus it cuts down in pointless boilerplate code, and makes the code easier to read. This is, of course, predicated on the quality, length and design of the function in question. If it's a haphazard 500-line mess of spaghetti that ignores good coding practices (such as the SOLID principles), then yeah you might need to explicitly scope stuff. But - again - that's down to the code being poorly implemented. Not about scoping per se. And obvs(?) if one is maintaining legacy code there is an increased likelihood of it fitting the description of "haphazard 500-line mess of spaghetti that ignores good coding practices (such as the SOLID principles)", so... yeah... act accordingly. I did not mean that as an indictment of anyone writing new code today; it's an indictment of the code they're writing into.
z
Only 500 lines? 🙏
head desk 1
a
I was being kind
😉
r
Some of us dream of working with spaghetti of only 500 lines 🙂
a
Hey, in that the code is even in functions so we are getting to discuss the local scope is an improvement on some code I see... [cough]... sometimes.
z
Try harder, there's a 64k limit in java for class size....
😜 1
a
In a previous life we did indeed butt-up against that sometimes. Dreadful.
z
Yeah the nifty luceedebug step debugger had problems with that too
(most promising google result out of the first few)
z
That's the project! By @David Rogers
1