Create an instance of a class when declaring a variable or inside a constructor

Possible duplicate:
Where is the โ€œrightโ€ place to initialize class variables in AS3

I was wondering if anyone knows that it would be better to instantiate the class in this variable declaration or inside the constructor? For example, this:

protected var _errorHandler:ErrorHandler = new ErrorHandler(); 

or that:

 protected var _errorHandler:ErrorHandler; public function someClass() { _errorHandler = new ErrorHandler(); } 

A small point that I think of, but I want my code to be as reliable and efficient as possible!

thanks

Chris

+6
source share
1 answer

Initialization in the constructor is preferable, for readability - for the ability to easily see what is initialized when. The least readable option would be to mix them, which I cannot recommend.

There is a third option that you will use for AS3 programmers:

  • No initialization in variable declarations
  • Empty (or almost empty) constructor
  • All initialization performed in one or more selected init () functions

This approach offers two possibilities:

  • You can easily reset the object for reuse by calling init again
  • You can get around the limitation that AS3 does not allow to overload the constructor, like other similar languages โ€‹โ€‹(Java / C ++ / C #). For example, you might want to initialize a data structure with one or more types of objects.

In terms of performance, I believe that your two examples will come down to the same byte code. The AS3 compiler creates a special class initializer for static declarations that are outside the constructor, but for regular member variables initialized during the declaration, I expect it to just move the initializations inside the constructor for you. But does he push them forward or after what is clearly in the counter-structure? I donโ€™t remember, so I quote readability as the main reason to put everything in the constructor yourself :-)

+7
source

Source: https://habr.com/ru/post/885827/


All Articles