Whatterz


Implicit Structures in ColdFusion 8

by Simon. Average Reading Time: about 3 minutes.

In an earlier post I eluded to the implicit creation of arrays in ColdFusion 8. Well, the same can be said of structures.

A structure, also known as an associative array, is a complex data type composed of a collection of keys and a collection of values, where each key is associated with one value (a key-value pair). The operation of finding the value associated with a key is called a lookup or indexing, and this is the most important operation supported by a structure. The relationship between a key and its value is sometimes called a mapping or binding. For example, if the value associated with the key “Age” is 29 and “City” is “London”, we say that our structure maps “Age” to 29 and “City” to “London”.

Using structures, you can call the array element you need using a string rather than a number, which is often easier to remember. The downside is that these aren’t as useful in a loop because they do not use numbers as the index value.

We can think of an address book as a good example of a structure. The classic way of creating and assigning key-values pairs to a structure, in earlier versions of ColdFusion, would be as follows:

<cfscript>
strPerson = structNew();
strPerson.firstName = "Jean";
strPerson.lastName = "Dupont";
strPerson.city = "Paris";
</cfscript>

Or an alternative method uses array-notation to create the necessary key-value pairs:

<cfscript>
strPerson = structNew();
strPerson["Firstname"] = "Hans";
strPerson["Lastname"] = "Mustermann";
strPerson["Country"] = "Germany";
</cfscript>

NB. When using the array-notation, the key names keep their case. However, running the following code results in the value “France” being overwritten with “Germany”, even though the key name is a different case. This serves to highlight that ColdFusion is not case-sensitive.

<cfscript>
strPerson = structNew();
strPerson["Country"] = "France";
strPerson["COUNTRY"] = "Germany";
</cfscript>

Implicit Structures

With the introduction of implicit structures in ColdFusion 8, the creation of structures is greatly simplified. For example, rather than having to use the structNew() function, we can now simply do the following:

Using strings for values:

<cfscript>
myStruct = {firstname="Simon", lastname="Whatley", city="London"};
</cfscript>

Implicit Structures - Strings as Keys and Values

Using integers for values:

<cfscript>
myStruct = {account_no=12345678, sort_code=123456};
</cfscript>

Implicit Structures - Integers as Values

Using integers as keys:

This example most closely represents an array since arrays have numeric keys.

<cfscript>
myStruct = {10001="John", 10002="Doe", 10003="New York"};
</cfscript>

Implicit Structures - Integers as Keys

The integer could represent the unique identifier of an object, for example, user ID or order ID. Therefore, if we had nested structures like below, 10001 would be the ID of Simon Whatley, whilst 10002 would be the ID of John Doe.

<cfscript>
myStruct1 = {firstname="Simon", lastname="Whatley", city="London"};
myStruct2 = {firstname="John", lastname="Doe", city="New York"};
myStruct3 = {10001=myStruct1, 10002=myStruct2};
</cfscript>

Implicit Structures - Nested Structures

Mixed data types:

It is possible to mix the data types in an structure. For example, we can use an Integer, String and Array as elements within an array, with no problems. Since we need to know the key name before accessing the value, it is also likely we will know the type of the value and will be able to handle it accordingly. However, never assume this is always the case, so type checking is necessary when retrieving the data.

The example below demonstrates the ability to add arrays to structures.

<cfscript>
myArray1 = [1,2,3];
myArray2 = ["One","Two","Three"];
myStruct = {array1=myArray1, array2=myArray2};
</cfscript>

Implicit Structures - Nested Arrays

Structures, by their nature, cannot be sorted by value, only by the key name. They are best for related data, where order is not important and direct access to an individual element is important. Many of ColdFusion’s variable scopes can be accessed as structures, for example, Server, Application, Session and Variables etc.

Words of Caution

Implicit structures do have their limitations. For example, you cannot nest implicit struct, or indeed array, creation.

<cfscript>
myStruct1 = {
	myStruct2 = {
		firstName = "Jean",
		lastName = "Dupont",
		country = "France"
	},
	myStruct3 = {
		firstName = "Juan",
		lastName = "Pablo",
		country = "Spain"
	}
}
</cfscript>

The above will throw the following parsing error:

coldfusion.compiler.ParseException:
Invalid CFML construct found on line 3 at column 10.

UPDATE: The recent ColdFusion Update now includes the ability to nest implicit structures.

To get around this problem, you can create each structure individually and then use the structure as the value in a key-value pair (as seen in the nested structure example above).

A (possible) strength of ColdFusion is that you can add key-value pairs as many times as is necessary. This is the same for explicit and implicit structure creation. However, the following code and screenshot serves to demonstrate that whether you explicitly or implicitly create a structure, if you duplicate a key, the last key-value pair in the sequence is the one that is represented in the structure:

<cfscript>
myStruct = {
	firstName = "Jean",
	lastName = "Dupont",
	country = "France",
	country = "Germany"
};
</cfscript>

Implicit Structures - Duplicate Keys

This article has been tagged

, , , , , , , , , , , , , , , , , , , ,

Other articles I recommend

Implicit Arrays in ColdFusion 8

A great new feature of ColdFusion 8 is its new implicit creation of Arrays and Structures. In addition to the updates to operators in ColdFusion, those of you familiar with JavaScript will recognise and welcome these changes.

An array is a data structure consisting of a group of elements that are accessed by indexing. In most programming languages each element has the same data type. However, ColdFusion, as we will see, is not strictly typed and therefore allows any data type to be stored in combination. This allows strings, integers, booleans and other complex data types all to be stored in the same array. However, doing this certainly isn’t a good practice as it causes signification complication when accessing the stored data.

Variables of a simple data type commonly only store a single value but, in some situations, it is useful to have a variable that can store a series of related values – using an array. Arrays are described as complex data types because they can hold data in a structured, complex way.

The Inner Workings of a ColdFusion Array and Structure

Array and Structures are considered to be complex data types in ColdFusion. In contrast, simple data types are ones that contain a single piece of data, such as an Integer, String, or Boolean value. A complex data type can contain multiple pieces of data, which, in the case of arrays, are usually related. All the data are referenced under a single variable name. You can think of a complex variable as a variable that contains a collection of other variables inside it. An array maps Integers to arbitrarily typed objects (Integers, Strings, Booleans and Objects) while a structure, or associative array, maps arbitrarily typed objects to arbitrarily typed objects.

The Java Behind a ColdFusion Array and Structure

Following a conversation with a friend regarding how ColdFusion handles arrays and structures in ‘the background’, I was interested to find out what Java classes each were mapped to. This was a relatively simple case of using the functions getClass(), getSuperClass() and getName() to parse out the name of the Java classes.

  • Simon,

    Your series have been very informative. At first they may seems to be a review but you always sneak in nuggets of gold (in this case the error when nesting structures) that hopefully will sink into my brain this time.

    So, when are you going to start the multi-week series to provide the definitive guide to everything that can be accomplished with cfajaxproxy?

  • I’m glad you like the articles. It is funny you should mention cfajaxproxy; it is an area I was discuss with a friend recently.

    All I can say is watch this space…

  • Jordan

    Good news, with the 8.1 update release you can now created nested implicit structures and arrays!

  • Jono

    Hi I’m new in CF, i’m trying to call a method from a cfc that returns a array with objects (with gets and sets), but I can’t cast the objects inside it, it comes as a struct, is there any way to do this? by the way i’m using cf 8. thanks

  • Simon,

    This is a good article. I do have some clarifictions though. In your examples with implicit structure definitions, the keys change their case to upper case. However, you can create an implicit struct that keeps case by simply wrapping the keys in quotations.

    will keep it’s case.

  • @tristan that’s right. If you use array notation, you’re able to keep the case of the structure names, e.g. myStruct["myKey"] = "myValue". This will produce a key called “myKey”. However, using dot notation, e.g. myStruct.myKey = "myValue", will result in the key being upper case.