I've noticed in a lot of people's classes that they prepend variables with an underscore and use custom getters and setters.
Why is this? Is it for performance reasons? How/why is a custom getter better then getting a variable normally?
Printable View
I've noticed in a lot of people's classes that they prepend variables with an underscore and use custom getters and setters.
Why is this? Is it for performance reasons? How/why is a custom getter better then getting a variable normally?
When you have a getter/setter, its often that the getter/setter property relates to a private (or protected) variable defined in the class. Because the getter/setter and the variable cannot have the same names, its common that the private variable will be named the same but with a preceding underscore. It doesn't have to be named this way, but it's pretty standard.
The advantages of using a getter/setter is that you can call methods or perform other actions when the value is set or accessed. Additionaly, by using a getter/setter the property can be overridden. For example, if you're familiar at all with AS2, you'll know that you couldn't override the _x and _y properties of MovieClips. Because those properties are now inherently getter/setters in AS3, you can override them and add new functionality in your AS3 classes.
Getter/setter properties are NOT however, good for performances. You'll notice that some classes like Point and Rectangle do not use them for some of their properties for this very reason. If performance is of concern, you would want to stay away from them if possible. Otherwise they're very useful for creating flexible and extendible classes.
Cool. Thanks for the explanation :)