Handling Null in ColdFusion 👨‍💻

Handling Null in ColdFusion 👨‍💻

CF uses duck typing to deal with variable types: if it quacks like a date, it must be a date.  More on duck typing

When ColdFusion gets a null back from a Java function, it is much like a duck through a jet engine.  It is going to happen eventually and the results range from gross to catastrophic.

The ColdFusion language doesn’t really consider null a possibility but CF is built on top of Java and null values can exist in Java.  If you call a function from a Java object and assign the result to a variable, that variable can become null.

<cfset myJavaReturn = CreateObject("Java","com.coldfusionpowered.xmp.NullFactory").getNull()/>

ColdFusion doesn’t differentiate between a variable that has been set to a null value and a variable that was never set at all.  In our example it will appear as if myJavaReturn never existed!  As a CF developer you have several options to deal with this:

  1. Politely ask your Java developer not to return null
  2. Use a function like StructKeyExists() or IsDefined() to check for null after your call
  3. CFParam your variable after the assignment
  4. Wrap your function call in a UDF that ensures that a value is returned
  5. isNull() in CF9+
  6. Suggestions?

Many times, suggestion one is not possible.  You maybe working with an established API or a middle tier that services more than just ColdFusion.  You may just get laughed at and ridiculed by the Java devs for your arrays starting at index 1.  Fortunately, checking the result isn’t hard in simple cases:

<!--- we can also create nulls in CF with a JavaCast --->
<cfset myJavaReturn = JavaCast( "null", "") />
<cfif not IsDefined("myJavaReturn")>
<cfset myJavaReturn = ""/>
</cfif>

If you have to do this a lot, you may want to wrap this up in a cffunction:

<cffunction name="AntiNull" hint="Assist with null values returned from Java, Returns an empty string if target is null.">
<cfargument name="target" default=""/>
<cfreturn arguments.target />
</cffunction>
<cfset myJavaReturn = antiNull(JavaCast("null",""))/>

I hope that helps you deal with nulls in CF.  If you have another method for dealing with this, I’d love to hear it!  Please comment.

whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.