Encapsulation

One of the rules of good object-oriented design is that all classes should be black boxes: you can put things in and take things out, but you can’t determine how it operates. In other words, the only way to interact with a class instance is to use its public methods. You should never be able to look into an object or change the object’s state except by asking the object to tell you about itself or to change its own state. The object must always maintain sovereignty. The minute an object is no longer in charge of its own internal world, the entire object-oriented universe starts to crumble and fall apart into an unmanageable train wreck.

This idea of classes being black boxes is a fundamental principle of object-oriented design called encapsulation. Encapsulation is absolutely necessary for an object-oriented design to succeed because it enables objects to interact with one another in known and well-defined ways.

This approach models the world in which we live in many ways. Every object in the physical world has boundaries that define it and its interface with the world around it. Your body interacts with the air by way of respiration, for example. Without these well-defined interfaces there would be chaos, and it would be impossible to interact with anything in a useful or meaningful way.

Using private variables instead of pulic

The easiest way to insure encapsulation is to use private variables. The private statement in ActionScript 3.0, whether it’s used with variables, constants or methods (functions) makes sure that only the class that defines or declares it can use it. This not only shuts out implementations that attempt to assign any value they want, but it also excludes subclasses.

The get and set methods

The best way to maintain encapsulation and hide the information in your objects is to use the ActionScript 3.0 get and set methods.

package
{
    public class Person
    {
        private var personName:String;

        public function Person( ):void {}

        //Getter function
        public function get pName( ):String
        {
            return personName;
        }

        //Setter function
        public function set pName(value:String):void
        {
            personName = value;
        }
    }
}

Keep in mind that pName is a method, and not a property. However, setting and getting values using the pName() method looks exactly like setting and getting a property value.

External References

A class should never directly reference any object that is outside of itself unless it obtains that reference through its public interface. A class can declare private properties and local variables and can reference those objects internally because they exist within the class. A class can also reference an outside object if the reference was passed into it via a public method.

Post A Comment

Anti-Spam Quiz: