views:

34

answers:

2

Is it "better" to initialize AS3 class variables in the class constructor? Or can I just initialize them to their default value when I declare them at the top of my class? I ask because when there's a lot of class variables, it appears inefficient to declare them in one place and then initialize them in another when I could easily do both in the same place. It one option is better than the other, why?

Thanks!

eg:

initializing in constructor

class foo {
    var bar:Boolean
}

function foo():void {
    bar = true;
}

OR

initializing with the declaration

class foo {
    var bar:Boolean = true;
}

function foo():void {
}
+1  A: 

I personally recommend initialization inside the constructor for two reasons:

  1. You cannot initialize objects that depend on other var objects having already been created before construction.
  2. It's easier to locate and understand initialization code when it's properly procedural. Especially when you (I) dive back into big classes I haven't opened for months.
Ben
+1  A: 

Personally I don't do either. I like to create an init function that initializes everything. That means if need to reset the an instance to its default, I can just call the init method at anytime.

TandemAdam