Pergunta

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>
Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top