Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Saturday, April 19, 2008

Flex Tip: Publicly Accessible Private Variables in a Flex Class Or Another Reason to use Getters and Setters

I've really fallen in love with using Getters and Setters for requesting and updating variable values in my flex classes. The most obvious reason for using Getters and Setters is having the ability to run some logic each time the value of a variable is updated or requested.

Another elegant reason to use Getters and Setters which I've just stumbled upon is the ability to have a variable which is bindable and can be accessed publicly but can only be modified privately. I'll let you come up with your own reasons why this is useful. For me I wanted a custom component to be responsible for managing it's own state but needed the ability for other components to determine it's current state.

Here's an example of how you might be used to working with variables. You have one variable which can be accessed or updated publicly and another which is just for internal use.

// a publicly accessible variable with binding
[Bindable] public var currentState:String;
// a private variable
private var internalState:String;

// You could use a private function to update both variables.
private function updateCurrentState(value:String):void
{
this.currentState = value;
this.internalState = value;
}
The above code would work to meet my requirements but it's an obviously flawed and confusing approach. However without using Getters or Setters it would be the easiest way to meet the requirements.

Here is how you can use Setters and Getters which let you use one variable that can be accessed publicly but only updated internally. Just use a public scope declaration on the get function and a private scope declaration on the set function. Easy and elegant.
private var _currentState:String;

[Bindable] public function get currentState():String
{
return this._currentState;
}
private function set currentState(value:String):void
{
this._currentState = value;
}

No comments:

Post a Comment

Thank you for the comments.