PDA

View Full Version : Setting Default Values in Ctor


sixtyfootersdude
07-31-2008, 01:23 PM
Ran into a curious problem/bug. Mostly just curious about why this is happening because I can obviously make a work around.

I have a date object and I want to keep the default value so that I can check to see if it is the default later. Unfortunately this does not work:


package{
public class MyDate{

public var date:String; //Date in the form 2008-01-23

private var defaultStr:String = "UNKNOWN";

public function MyDate(date:String=defaultStr){
this.date=date;

}
//....
}
}

I am inclined to think it is b/c of the program flow. It does not create defaultStr until after it runs the constructor.

This code does work:

package{
public class MyDate{

public var date:String; //Date in the form 2008-01-23

private var defaultStr:String = "UNKNOWN";

public function MyDate(date:String="UNKNOWN"){ //<-Change from defaultStr to "UNKNOWN"
this.date=date;

}
//....
}
}

But it seems like bad practice because a maintenance programmer would have to change the default in two places and could easily forget.

Just curious why i cannot set date:String=defaultStr

Slowburn
07-31-2008, 03:04 PM
use a constant instead of a regular var. constants are evaluated at compile time, not runtime.


package
{
public class MyDate
{

public static const DEFAULT_DATE:String = "UNKNOWN";

public var date:String;

public function MyDate( date:String = DEFAULT_DATE ):void
{
this.date = date;
}
}
}

sixtyfootersdude
07-31-2008, 04:19 PM
Thanks Slowburn just what I was looking for.

J