Scope Nazi
Some people are anal retentive about not using pound signs where they aren't necessary (my boss), some people are anal retentive about var-scoping local variables in components (Ray Camden); and then there's Me. I'm anal retentive about scoping all of your variables. Consider this. When you execute this line of code:
<cfset foo="bar">
There is only one thing that could happen: A variable in the "variables" scope is set with the value "bar". (Unless you're in a CFC, in which case you should be using var scope, like Ray advocates. ;) On the other hand, when you execute this line of code:
<cfif foo is "bar">
The value could potentially be read from one of NINE scopes, in MX7. To clarify, I'm fine with implying your variable scope, however, it irks me to no end when you infer your variable scope. (What's the difference between implying and inferring?) To wit, a colleague pointed out that she was having issues with this code:
<CFQUERY name="orders" datasource="#application.DS#">
SELECT distinct ORDERS.ord_id, ORD_placedOn, ORD_billFirstName, ORD_billLastName,
ORD_Total, Ord_Total + isnull(Adjust_total,0) as net_sales, ORDERS.OSTATUS_id,
ord_assignedTo, OSTATUS_name, orders.ORD_shipAmount, p.prod_assembly_reqd
FROM ORDERS, OrderStatus, payflowpro,
(Select ord_id, sum(adjust_total) as adjust_total from Order_Adjust where result=0 group by ord_id) as Order_Adjust,
Order_Item OI, Item_View I, Product P, ordershipaddr osa
WHERE ord_completed = 1
AND ...
</CFQUERY>
<cfoutput query="orders">
<cfquery name="getManu" dataSource="#application.DS#">
select distinct man_name, manufacturer.man_id, item_name, album_id
from Order_Item, item_view as item, product, manufacturer
where order_item.ord_id=#orders.ord_id#
and item.item_id=order_item.item_id
and item.prod_id=product.prod_id
and product.man_id = manufacturer.man_id
</cfquery>
<cfloop query="getmanu">
<cfif (listfind(application.vendor_inhouse_list,man_id) gt 0 or
listfind(application.inhouse_album_list,album_id) gt 0) and
prod_assembly_reqd eq 'Y' and
oitem_sample neq 1>A<cfelse> </cfif>
</cfloop>
</cfoutput>
The issue was that sometimes the variable prod_assembly_reqd was undefined. The resolution was simply to use proper scoping. This is the code I sent back:
<cfif (
listfind(application.vendor_inhouse_list, variables.getManu.man_id) gt 0
or
listfind(application.inhouse_album_list, variables.getManu.album_id) gt 0
)
and
variables.orders.prod_assembly_reqd eq 'Y'
and
?????.oitem_sample neq 1
>A<cfelse> </cfif>
Using explicit scoping like this leaves zero room for confusion where the data is coming from. The last line, where I used the scope "?????", I noted that this is probably inferring the Variables scope, but that she should check on it and make sure she indicates which it is.
in Best Practices | ColdFusion Posted 2007-07-24 06:48





