Skip to main content
Ben Nadel at CFCamp 2023 (Freising, Germany) with: Mark Drew and Michael Hnat
Ben Nadel at CFCamp 2023 (Freising, Germany) with: Mark Drew Michael Hnat

Handling NULL Values In ColdFusion

By
Published in Comments (1)

There have been some NULL value discussions taking place lately on the House of Fusion CF-Talk list. Null values in ColdFusion can be very tricky. There are null values in a database, which I have discussed before, and there are NULL values as variable data. In my experience, there are no Null values in ColdFusion variable data, and in fact, if you set a variable to NULL (via some non-cf call), the variable itself gets destroyed.

Take as an example, reading in a ZIP file. To do so, you have to keep streaming in zip entries until you hit, in Java, a null value. In Java, you would do something like:

while (objZipEntry != null){ ... }

In ColdFusion however, putting a null value into objZipEntry will actually destroy it and remove it from its parent variable scope. So, the equivalent in ColdFusion would be:

// Loop while we did not hit a "null" value.
while (StructKeyExists( REQUEST, "ZipEntry" )){
	// .... more code here ....

	// Get the next zip entry (finish if null).
	REQUEST.ZipEntry = REQUEST.ZipInputStream.GetNextEntry();
}

As you can see, we have set the ZipEntry variable into the REQUEST scope (not shown in the code). Then, for each while loop iteration, we get the next zip entry. Once the Java object ZipInputStream returns null, signaling the end of the zip entry streams, ColdFusion "executes" that null value by removing the ZipEntry key from the REQUEST scope.

In order to handle this well, I would suggest scoping all values that might receive null values. You can use the VARIABLES scope, but my personal choice would be REQUEST or some other custom struct.

Want to use code from this post? Check out the license.

Reader Comments

3 Comments

The request scope is slightly dangerous since it's globally available to all objects, methods, etc within the given request. You run some chance of colliding with another variable in that scope, especially in larger applications. A local scope is much safer, this, variables, or a struct you create for this purpose.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel