Thursday, June 25, 2009

Encapsulation


Now let's move on to another important principle of OOP called encapsulation. The underlying concept of encapsulation deals with what methods and properties your class exposes to the outside world.

Up until this point you've always set methods and properties as public, but is that really what you'd want to do?

If you want your code to be stable, and if you want to develop projects that are least prone to bug and errors, you'll want to restrict the ways in which other classes can interact with your code.

The key here is to only have those methods and properties available that are required as settings for the class, and restrict access to the rest. Using this approach, you'll have a limited number of places in your code to debug when something goes wrong in the interaction with your class.

ActionScript 3.0 includes the following keywords as access modifiers to methods and properties:

  • public: allows access from anywhere
  • private: can only be accessed within its own class
  • protected: can only be accessed within own class and subclasses
  • internal: can be accessed by all classes in same package

Let's put this concept into practice. Take a look at the following example:

Person.as

package com.adobe.ooas3 {
public class Person {
private var _age:Number;

public function get age():Number {
return _age;
}

public function set age(val:Number):Boolean {
if(_age < _age =" val;">

The code example above shows a Person class with a private property _age of a Number type. Even though you want to allow the age of the person to be set, you still opted not to use a public property here. Instead you are routing the age value through the use of a getter/setter method.

Getter/setter methods (as implemented in the previous example) appear as if they are properties, but they behave like methods.

When you set the age property, it calls the age setter method that assigns the value to the private _age property after validating it. In this case, you know that a person's age can't be a negative value. If the given value is valid, the setter method returns true, or else returns false.

The major advantage of this approach is that every time the age property is set, validation occurs because the age value is always routed through the setter function. If the age property were set as public, every method in your class that wants to use the age property would first need to check if its current value is valid.

No comments:

Post a Comment