REALbasic Cross-Platform Application Development

In practice, encapsulation is practiced by setting the scope of methods and properties. You've already encountered the idea of scope in the section on modules, but it takes on much greater importance when you're working with classes.

The whole point of encapsulation is that you want your objects to have a little modesty; not everything has to be hanging out in public for the whole world to see. The reason this is a good idea when programming is the same reason you don't want to do it personally. When things are exposed, other people have access to things they should not have access to and can thereby cause mischief. You might get sunburned or pregnant. Encapsulation, like modesty, is a virtue.

You only want to expose those parts of you that others have any business dealing with. Keep everything else safely tucked away.

When it comes to deciding how much of yourself you expose to others, or what others are allowed to do to or with you, it really depends on who that other person is.

Have you ever noticed that it's okay for you to make fun of your mom or dad or sister, but it's not okay if one of your friends does? What's considered acceptable behavior changes according to whether you're one of the family or not one of the family. Being a member of the family is a privileged position.

There are also some things that only certain members of the family are able to do, like drink beer out of the refrigerator. The kids and their friends don't get to do it because that's dad's beer and nobody is going to touch it.

This is how encapsulation works. If a method is protected, it's a method that you're keeping "in the family." Subclasses can call the method, but unrelated classes cannot. A method can also be designated as private, which is like Dad's beer stash. Only dad and no one else, not even his firstborn, can drink his beer. It's dad's private beer supply. A private method can be called only by the method that implements it, and no other classes, superclasses, or subclasses can touch it.

Recall that we have dealt with access scope before, when working with modules. The way that access scope is handled in modules is slightly different, with an emphasis on avoiding namespace collisions.

With classes, these terms have the following meaning:

  • PublicAny other object or module can access this class member.

  • ProtectedOnly members of this class or subclasses of this class can access this member.

  • PrivateOnly this class can access this member; subclass members cannot.

Категории