Tuesday, August 18, 2009

when null is not null

Having just left the debugging Twilight Zone, I am going to post my findings so that others can profit from my woes.

I had a simple if statement like this:

if ( someValue == null ) trace( "null" );
else ( trace( "not null" );

I expected the value to be null, so I was surprised to see "not null" appear in the output window.

To check my sanity, I added a trace above the conditional:

trace( "someValue == ", someValue );
if ( someValue == null ) trace( "null" );
else ( trace( "not null" );

To my horror, I got this:

someValue == null
not null

After half an hour of tripping in Bizarro World, I noticed those extra spaces before the word "null" in the first trace. This prompted me to take a look at someValue's declaration:

var someValue : String = myFlashVars.someValue;

myFlashVars is, as you might guess, an object containing all the flashVars. I expected someValue to be null, because, while testing, I wasn't passing any vars into the swf.

Okay, I lied. The declaration wasn't this...

var someValue : String = myFlashVars.someValue;

... it was this:

var someValue : String = unescape( myFlashVars.someValue );

Since myFlashVars got set with URL variables (e.g. http://myapp.swf?someValue=foo), I wanted to make sure that any escaped characters in someValue got converted to unescaped ones.

But this causes a problem when there is no myFlashVars.someValue. If there is no myFlashVars.someValue, then myFlashVars.someValue = null.

And, apparently, if you unescape null, you get the string " null".

So my conditional was testing whether " null" is equal to null. And of course it's not.

No comments:

Post a Comment