ColdFusion:在CFC中省略variables关键字是否安全?

Pat*_*ney 5 coldfusion cfc

在ColdFusion组件(CFC)中,是否有必要对变量范围的变量使用完全限定名称?

如果我改变这个,我会不会遇到麻烦:

<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>
Run Code Online (Sandbox Code Playgroud)

这个?

<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>
Run Code Online (Sandbox Code Playgroud)

Sol*_*nal 10

创建变量时指定"变量"无关紧要,因为默认情况下foo将放在变量范围内; 但是当你访问变量时它会很重要.

<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>
Run Code Online (Sandbox Code Playgroud)

doSomething("args")返回"我有args函数局部变量 "

doAnotherThing("args")返回"我有一个变量的私有实例和一个函数局部变量."


小智 6

我会说是的.这显然是必要的吗?不.你可以逃避不做吗?当然.你在找麻烦吗?绝对.如果你在cffunction中有以下内容:

<cfset foo = "bar" />
Run Code Online (Sandbox Code Playgroud)

这不会将该变量放在函数local var scope中,它会将它放在CFC的全局VARIABLES范围内,这意味着它可用于该CFC的每个方法.有时你可能想要这样做,但大多数时候你会要求竞争条件.

当服务器正在读取任何变量时,如果该变量不是作为范围的一部分声明(REQUEST.,SESSION.等),那么ColdFusion将运行ScopeCheck()来确定变量所在的范围.不仅这会给您的应用程序服务器带来不必要的开销,它还会引入劫持功能,即您的变量位于一个范围内,但ScopeCheck()已经在优先顺序中找到了同名的变量.

始终,始终,始终,范围所有变量.无论多么微不足道.甚至包括查询名称和循环索引.从痛苦中拯救自己,以及那些来到你身后的人.


Dan*_*son 5

特别是在CFC中,适当的范围是重要的.额外的"冗长"值得清晰.将变量从其入侵范围中移除将导致严重问题并且很难诊断.

冗长并不总是坏事.我们以getAuthenticatedUser()等描述方式命名我们的函数和方法,而不是gau().数据库列和表最好是描述性的,如EmployeePayroll而不是empprl.因此,当您的短期记忆充满项目细节时,简洁可能会"更容易",但描述性显示您的意图并且在应用程序的维护阶段有用,在您的短期记忆充满其他东西很久之后.