Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ColdFusion: Is it safe to leave out the variables keyword in a CFC?

Tags:

coldfusion

cfc

In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?

Am I going to get myself into trouble if I change this:

<cfcomponent>
    <cfset variables.foo = "a private instance variable">

    <cffunction name = "doSomething">
        <cfset var bar = "a function local variable">
        <cfreturn "I have #variables.foo# and #bar#.">
    </cffunction>
</cfcomponent>

to this?

<cfcomponent>
    <cfset foo = "a private instance variable">

    <cffunction name = "doSomething">
        <cfset var bar = "a function local variable">
        <cfreturn "I have #foo# and #bar#.">
    </cffunction>
</cfcomponent>
like image 615
Patrick McElhaney Avatar asked Sep 12 '08 15:09

Patrick McElhaney


2 Answers

It won't matter to specify "variables" when you create the variable, because foo will be placed in the variables scope by default; but it will matter when you access the variable.

<cfcomponent>
    <cfset foo = "a private instance variable">

    <cffunction name="doSomething">
        <cfargument name="foo" required="yes"/>
        <cfset var bar = "a function local variable">
        <cfreturn "I have #foo# and #bar#.">
    </cffunction>

    <cffunction name="doAnotherThing">
        <cfargument name="foo" required="yes"/>
        <cfset var bar = "a function local variable">
        <cfreturn "I have #variables.foo# and #bar#.">
    </cffunction>

</cfcomponent>

doSomething("args") returns "I have args and a function local variable"

doAnotherThing("args") returns "I have a private instance of a variable and a function local variable."

like image 117
Soldarnal Avatar answered Jan 03 '23 14:01

Soldarnal


Especially in CFCs, proper scoping is important. The extra 'verbosity' is worth the clarity. Having variables slip out of their indended scope will cause severe problems and very hard to diagnose.

Verbosity isn't always a bad thing. We name our functions and methods in descriptive manners like getAuthenticatedUser(), rather than gau(). Database columns and tables are best left descriptive like EmployeePayroll rather than empprl. Thus, being terse might be 'easier' when your short term memory is full of the project details, but being descriptive shows your intent and is helpful during the maintenance phase of an application, long after your short term memory has been filled with other stuff.

like image 29
Dan Wilson Avatar answered Jan 03 '23 16:01

Dan Wilson