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:
- Politely ask your Java developer not to return null
- Use a function like StructKeyExists() or IsDefined() to check for null after your call
- CFParam your variable after the assignment
- Wrap your function call in a UDF that ensures that a value is returned
- isNull() in CF9+
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.