Arguments and Return Values and NULLs ... oh MY!

I had thought the argument monster had finally died with my last post. But noooo. There's yet another wrinkle, and this time it is actually not my fault.

Consider the following code.

<cffunction name="foo">
<cfargument name="param1" required="false" />
<cfargument name="param2" required="false" />

<cfdump var="#structKeyExists( arguments, "param1" )#" />
<cfdump var="#structKeyList( arguments )#" />
<cfdump var="#arguments#" />

<cfset bar( argumentCollection=arguments ) />

<cffunction name="bar">
<!--- do nothing --->

<!--- Run the function --->
<cfset foo() />

Okay, so guess what you see? First, you'll notice the obvious "NO" coming from the structKeyExists() function. We expect that, and love it for behaving as expected.

And now it just starts getting a little weird. You'll notice the list of arguments has both "param1" and "param2" in the list. What? I didn't pass in any values why would they be in the list, especially if they don't 'exist'? Well, take a look at the next output.

The dump of the arguments struct provides the answer. Notice that pesky little phrase 'undefined struct element'? CF has predefined the argument collection keys, and then places the corresponding values. Since there was no value passed, the java side of CF places NULLs into their slots. The structKeyExists() function correctly determines existence if the value is NULL, but that's in java. CF doesn't have a way to directly detect for nulls.

Be very careful when dealing with non-required parameters and then passing the arguments struct off as an argumentCollection.

Just for kicks try this:

<cffunction name="nullify">
<!--- do nothing --->

<cfset foo = "Hello World!" />
<cfset foo = nullify() />

It's easy to spot the problem here, but in real world code where the offending function is more than likely in another file, it can cause a bit of a headache.

Be default the java methods that the CF code gets translated into will return a null value if a return value is not specified. The nullify function above essentially is the same as:

<cffunction name="nullify">
<cfreturn javaCast( "null", "" ) />

BlogCFC was created by Raymond Camden. This blog is running version 5.5.006. | Protected by Akismet | Blog with WordPress