About using encapsulation

In elegant object-oriented design, objects are seen as "black boxes" that contain, or encapsulate, functionality. A programmer should be able to interact with an object by knowing only its properties, methods, and events (its programming interface), without knowing the details of its implementation. This approach enables programmers to think at higher levels of abstraction and provides an organizing framework for building complex systems.

Encapsulation is why ActionScript 2.0 includes, for example, member access control, so that details of the implementation can be made private and invisible to code outside an object. The code outside the object is forced to interact with the object's programming interface rather than with the implementation details. This approach provides some important benefits; for example, it lets the creator of the object change the object's implementation without requiring any changes to code outside of the object, as long as the programming interface doesn't change.

An example of encapsulation in Flash would be setting all your member and class variables to private and forcing people who implement your classes to access these variables using getter and setter methods. Performing encapsulation this way ensures that if you ever need to change the structure of the variables in the future, you would need only to change the behavior of the getter and setter functions rather than force every developer to change the way he or she accesses the class's variables.

The following code shows how you could modify the Person class from earlier examples, set its instance members to private, and define getter and setter methods for the private instance members:

class Person {
    private var __userName:String;
    private var __age:Number;
    public function get userName():String {
        return this.__userName;
    }
    public function set userName(value:String):Void {
        this.__userName = value;
    }
    public function get age():Number {
        return this.__age;
    }
    public function set age(value:Number):Void {
        this.__age = value;
    }
}