Possible Duplicate:
Where is the “proper” place to initialize class variables in AS3
I was wondering if anyone knows wether its better to instantiate class on it's variable declaration or within a constructor? For example, this:
protected var _errorHandler:ErrorHandler = new ErrorHandler();
or this:
protected var _errorHandler:ErrorHandler;
public function someClass() {
_errorHandler = new ErrorHandler();
}
A small point I think, but I want my code to robust and efficient as possible!
Thanks
Chris
It makes sense to initialize the variable at declaration to avoid redundancy. It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors.
A constructor is typically used to initialize instance variables representing the main properties of the created object. If we don't supply a constructor explicitly, the compiler will create a default constructor which has no arguments and just allocates memory for the object.
Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
int x = 10 ; This creates a box called x with type int and writes a value of 10 in the box. The syntax for an initializer is the type, followed by the variable name, followed by an equal sign, followed by an expression. That expression can be anything, provided it has the same type as the variable.
Initialization in the constructor is preferred, for readability--for being able to easily see what gets initialized when. The least readable option would be to mix these, which I can't recommend.
There is a third option that you will see AS3 programmers use:
This approach has two things to offer:
As far as performance goes, I believe your two examples would compile down to the same byte code. The AS3 compiler makes a special class initializer for static declarations that are outside the constructor, but for regular member variables initialized at declaration time, I expect it just moves the initializations to inside the constructor for you. But does it move them ahead or after what is explicitly in the contructor? I don't remember, which is why I cite readability as a main reason to put everything in the constructor yourself :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With