Encapsulation

Encapsulation is the concept that an object should be a 'black box'. Another way to put this is that an object should totally separate its interface from its implementation.

This means that an object should completely contain any data it requires, and that it should also contain all the code required to manipulate that data. Programs should interact with our object through an interface, using properties and methods. Client code should never work directly with the data owned by the object.

In object-speak, programs interact with objects by sending messages to the object. These messages are generated by other objects, or by external sources such as the user. The way the object reacts to these messages is through methods. What Visual Basic calls properties would otherwise be called attributes.

Both Visual Basic 4.0 and 5.0 provide full support for encapsulation through class modules. Using these modules, we can create classes which entirely hide their internal data and code, providing a well-established interface of properties and methods to the outside world.

For example, if we create a class module and add the following code:

Option Explicit

Public Property Set Form(Target As Form)

End Property

Public Property Let CurrentX(X As Single)

End Property

Public Property Let CurrentY(Y As Single)

End Property

Then we've created an interface for the class. From here, we could do virtually anything in terms of implementing the class. For instance, we could just store the values:

Option Explicit

Private frmForm As Form
Private sngX As Single
Private sngY As Single

Public Property Set Form(Target As Form)
  Set frmForm = Target
End Property

Public Property Let CurrentX(X As Single)
  sngX = X
End Property

Public Property Let CurrentY(Y As Single)
  sngY = Y
End Property

Or maybe we just want to move to the coordinates:

Option Explicit

Private frmForm As Form

Public Property Set Form(Target As Form)
  Set sngForm = Target
End Property

Public Property Let CurrentX(X As Single)
  frmForm.CurrentX = X
End Property

Public Property Let CurrentY(Y As Single)
  frmForm.CurrentY = Y
End Property

Either way, we haven't changed the interface of the class, and so any program working with this class would have no idea if we have switched from one implementation to the other. This is the essence of encapsulation.

Obviously, the user might have a problem if we made such a change to our object. If applications were developed expecting the first set of behaviors, and then we changed to the second, there could be some interesting side effects. However, the point here is that the client programs would continue to function, even if the results were quite different than when we started.

We'll be making heavy use of encapsulation throughout this book, so you'll become very familiar with it if you haven't seen it before.

© 1997 by Wrox Press. All rights reserved.