문제

Is there a logical difference between the following two blocks? And is there one form more correct than the other? They would both reside in their own function--something I omitted here.

    <cfset local.result = 1 />
    <cfset local.i = 1 />
    <cfloop from="1" to="5" index="i">
        <cfset result = result * i />
    </cfloop>

And

    <cfset local.result = 1 />
    <cfset local.i = 1 />
    <cfloop from="1" to="5" index="i">
        <cfset local.result = local.result * local.i />
    </cfloop>
도움이 되었습니까?

해결책

Yes. In your second example you are making the exact same result; however, you have improved readability by explicitly identifying the scope you intend to modify--which is a good thing.

ColdFusion, will first search the LOCAL scope, so, you have not saved ColdFusion much processing; however, the code is cleaner now. If result existed in the CLIENT or COOKIE scope you would have saved ColdFusion the work of having to first evaluate four or five other scopes.

I once used to use the 'var result = 0;' style of localizing variables to a function, but, I now explicitly identify all my scopes to help ensure I have correctly scoped all variables and make the code easier to understand for others.

To summarize, the code is exactly the same to the machine but is now easier to understand for the human.

다른 팁

One suggestion... change:

<cfset local.i = 1 />
<cfloop from="1" to="5" index="i">

to

<cfloop from="1" to="5" index="local.i">

one less line of code, even more clear what's going on.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top