Handling Java Nulls In ColdFusion

Posted By : todd sharp Posted At : December 15, 2007 10:06 AM Posted In: Java, ColdFusion

2

I'm putting the finishing touches on my PowerPoint utils component when I came across a weird Java error. I've seen it before and it may very well be my lack of Java experience that is causing my lack of understanding here.

Say you have a Java method getFoo() that is expected to return a string. I've found that sometimes ColdFusion doesn't properly handle Java nulls so when you try to set a value you'll get something like so when trying to reference it:

Element foo is undefined in a CFML structure referenced as part of an expression.

ColdFusion cannot determine the line of the template that caused this error. This is often caused by an error in the exception handling subsystem.

It seems that ColdFusion simply chokes on it. I came up with a hacky fix by passing the value to another method which properly returns an empty string:

<cffunction name="fixNull" access="private">
    <cfargument name="valueToFix" default="" />
    <cfset rStr = "" />
    <cfif isDefined("arguments.valueToFix")>
        <cfset rStr = arguments.valueToFix />
    </cfif>
    <cfreturn rStr />
</cffunction>

Seems a bit hacky but it works. If someone can shed a little more light on the subject I'd appreciate it.

Comments (2)

rich's Gravatar Your understanding is correct...if a ColdFusion variable has its value set by a Java method, and that method returns null, the variable is dereferenced in ColdFusion. It ceases to exist at all, in any scope.

Your function should save you some keystrokes...I've gotten used to just putting if(isDefined("var")) after all my Java calls.

Michael Sharman's Gravatar Ben Nadel had a post or 2 on NULLs lately.

http://www.bennadel.com/blog/117-Handling-NULL-Val...