Sep 25 2008

Testing for null Objects

Published by at 2:27 pm under AS 3.0

I am not sure how many Flex/Flash programmers are aware of this fact or also you might call me to be a noob on this point but i discovered this today in AS 3.0, I just use ! to find if the object is null or not and don’t bother testing against another property within that object but sometimes there is no other way around it.

 

Consider the following example,

 

var strObj:Object = "";

//this is standard way of finding if the objects are null or not 

//since the object is initialized there should not be a trace

if (!strObj){ 

    trace("this shouldn't be happening");

}

But the trace statement shows up, it almost seems that Flash is treating this object as null but no if you look at the variable using the debugger the value is not null. So this isn’t the smartest way of checking if the object is null or not specially when you are dealing with strings.

 

Many people recommend doing it differently, like combing it with && for some property check of that object, it would look like this,

var strObj:Object = "";

//this is standard way of finding if the objects are null or not 

//since the object is initialized there should not be a trace

//ofcourse since this is string i am testing for length.

if (!strObj && strObj.length){ 

    trace("this shouldn't be happening");

}

Just something to keep in mind, its not always necessary.
 

2 responses so far

2 Responses to “Testing for null Objects”

  1. itzikon 28 Sep 2008 at 3:41 am

    why not:

    strobj != null

    ?

  2. Nayanon 28 Sep 2008 at 11:02 am

    duh…. for some reason tht thought never occurred to me ….. 😮

Trackback URI | Comments RSS

Leave a Reply