Always remember complex data types are passed by reference


I am working on a pet project currently that is written primarily in jQuery.  The initial state of the application is set by an  ajax call to a remote CFC method that sends back the data.  I was rushing through the CFC side of things trying to get the code written and came up with something similar to this:

<cfscript>
 result = structNew();
 appData = structNew();
 result['apps'] = arrayNew(1);

 appData['appName'] = "help";
 appData['windowTitle'] = "Help Content";
 appData['site'] = "";
 result['apps'][1] = appData;
 appData['appName'] = "cfbloggers";
 appData['windowTitle'] = "ColdFusion Bloggers";
 appData['site'] = "http://www.coldfusionbloggers.org";
 result['apps'][2] = appData;
</cfscript>

While this code is completely valid it definitely did not return the expected results.  Since ColdFusion passes complex data types (structures, components, and Java objects, etc.) by reference  both of the structures in my array elements contained the cfbloggers information instead of what I expected.  In the rush to get the code done, I forgot to set appData = structNew() after setting the first array element which would have returned the expected result.  A duplicate() would have worked equally well, but that is a bit of overkill for this simple application.

Edit: As Aaron pointed out, arrays are indeed passed by value as with other simple data types (strings, dates and numbers).

Advertisements

About Robert Zehnder

Web application developer specializing in ColdFusion/Railo and Open Source development.

Posted on March 5, 2010, in ColdFusion and tagged . Bookmark the permalink. 2 Comments.

  1. I was under the impression ColdFusion passed arrays by value.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: