Today I ran across two errors that I've seen many CF newbiews do in the past - so I thought I'd share them with you so you can watch out for them in your own code.
The first one involves lists. ColdFusion has many list functions. One of the common things people want to do is find an item in a list. However, many people accidently use the ListContains (or ListContainsNoCase) functions. This function will search each list item and see if it contains the string your are looking for. So, if your list is:
apples,boray,foo
and you want to find ray in the list, listContains will return 2, which means the second item contains the string ray. If you really want to find the item that is ray and is only ray, use ListFind or ListFindNoCase. (Did you know that there isn't an arrayFind()? You can find one at CFLib.org!)
The second error was more subtle. In almost all cases, when you do <cfset a= b>, you are creating a copy of b in a variable called a. However, if b is a structure, you have made a pointer instead. If you modify a, you will modify b as well. This can lead to headaches trying to figure out why b isn't working correctly. To remedy this, use duplicate instead. Do NOT use structCopy. structCopy will still return a variable with pointers if the structure contains structures itself.
Archived Comments
Just to be formal, you are creating a "reference" not a "pointer" -- it doesn''t really matter, but people who use compiled languages might not like you confusing the two. The main thing is that if you say FOO = BAR and bar is a struct, you now have a reference to BAR called FOO. But if you then do FOO = 0 you don''t actually change BAR by doing that. Also, objects (including component instances) and queries copy by reference as well. Unfortunately, duplicate() won''t work on object instances.
Good point Nathan! By the way - when you say object instances, you are speaking specifically about CFC instances, right? Do you know offhand if duplicate works on Java/COM objects?
No, as far as I know it does not work on java or COM objects. At least, I''ve seen it not work on Java. I never use COM, so I wouldn''t know there.
One way to get around it, for CFCs at least, would be to produce a clone() method for your CFC. Sure, it makes you do the work, but it would be handy. Another handy method (and kinda Java like) would be a toString() method.
Just rambling now. :)
The clone() is a nifty idea! I might try that out. :-) BTW, nice blog.
This is a test.
This is a test.
This is a test.