Chapter 4. Object-Oriented Programming

Object-oriented programming is a little different from earlier kinds of programming because it introduces programming constructs called objects, which contain both procedures and data. In this chapter we'll begin to understand what objects are and why they make programming easier and less prone to errors.

A procedural program is written in the style you are probably most familiar with: one in which there are arithmetic and logical statements, variables, functions, and subroutines. Data are declared somewhere at the top of a module or a procedure, and more data are passed in and out of various functions and procedures using argument lists.

This style of programming has been successfully utilized for a very long time as programming goes, but it does have some drawbacks. For example, you must be sure that the data are passed correctly between procedures, making sure that it is of the correct size and type. Thus, the procedures and their calling arguments may need to be revised frequently as a new function is added to the program during development.

Object-oriented programming differs in that a group of procedures are grouped around a set of related data to construct an object. An object is thus a collection of data and the subroutines or methods that operate on it. Objects are usually designed to mimic actual physical entities that the program deals with: customers, orders, accounts, graphical widgets, and so on.

More to the point, most of how the data are manipulated inside an object is invisible to the user and only of concern inside the object. You may be able to put data inside an object, and you may be able to ask the data to perform computations, but how it performs them and on exactly what internal data representation are invisible to you as you create and use that object.

Of course, a class (in VB) is actually just a template for an object. If you design a class that represents a Customer, you haven't created an object. An object is an instance of the Customer class, and there can, of course, be many such objects, all of type Customer. Creating a specific variable of a particular class type is referred to as instantiating that class.

Because objects contain data, you can regard them as having states. If you wrote a module of related functions, you probably would not have their behavior dependent on a variable somewhere, even if it is in the same module. However, when you write a class or object, you expect the various methods within the class to make reference to the data contained in that class and behave accordingly. For example, you might create a File object that can be open or closed, or at the end-of-file or not.

Once someone creates a complete, working object, it is less likely that other programmers will modify it. Instead, they will simply derive new objects based on it. We discuss the concept of deriving new objects in Chapter 5.

As we have noted, objects are really a lot like C structures or Pascal records, except that they hold both functions and data. However, objects are just the structures or data types. In order to use them in programs, we have to create variables with that data type. We call these variables instances of the object.

Building VB Objects

Let's take a very simple example. Suppose we want to design an object for measuring distance. Now, our first thought might have been to simply write a little subroutine to execute the measurement and then perform the measurement each time by calling this subroutine.

But in VB, we can write our code as a series of objects. So rather than writing subroutines, we do the following.

  1. Create a TapeMeasure class.

  2. Create instances of that class, each with a different size.

  3. Ask each instance to draw itself.

In VB, objects are represented as class modules. Each VB class is an object that can have as many instances as you like. When you write a VB program, the entire program is one or more classes. The main class represents the running program itself, and it must have the same name as the program file. In our example, the program is called Measurer.cls, and the main class is called Measure.frm.

Classes in VB contain data and functions, which are called methods. Both the data and the methods can have either a public or a private modifier, which determines whether program code outside the class can access them. Usually we make all data values private and write public methods to store data and retrieve it from the class. This keeps programs from changing these internal data values accidentally by referring to them directly.

If we want users of the class to be able to use a method, we, of course, must make it public. If, on the other hand, we have functions or subs that are only used inside the class, we would make them private. A VB program can be made up of any number of .cls and .frm files.

Creating Instances of Objects

We use the new operator in VB to create an instance of a class. For example, to create an instance of the TapeMeasure class, we could write the following.

Dim tp as TapeMeasure 'variable of type TapeMeasure

'create instance of TapeMeasure
set tp = new TapeMeasure

Remember, while we can create new variables of the primitive types (such as Integer, Single, and so on) we must use the new operator to create instances of objects. The reason for this distinction is that objects take up some block of memory. In order to reserve that memory, we have to create an instance of the object, using the new operator.

A VB Measurement Program

In the following example, we see a complete TapeMeasure class, including its measure routine.

'Tape measure class
Private width As Single, factor As Single

Public Sub setUnits(units As String)
'allows units to be cm or feet
 Select Case LCase$(units)
     Case "c":           'centimeters
        factor = 1
     Case "i":           'inches
        factor = 2.54
    Case Else
        factor = 1
     End Select
End Sub

Public Function Measure() As Single
  width = Rnd * 100#
  Measure = width / factor
End Function
Public Function lastMeasure() As Single
  lastMeasure = width / factor
End Function

The calling program is the Measurer form, which is merely the following.

Dim tp As New TapeMeasure

Private Sub btMeasure_Click()
txMeasure.Text = Str$(tp.Measure)
End Sub

Private Sub opCM_Click()
tp.setUnits "c"
txMeasure.Text = Str$(tp.lastMeasure)
End Sub

Private Sub opFt_Click()
tp.setUnits "f"
txMeasure.Text = Str$(tp.lastMeasure)
End Sub

Methods Inside Objects

As we noted previously, functions inside a class are referred to as methods. These functions can be public, meaning that you can access them from outside the class, or private, meaning that they can only be accessed from inside the class.

Variables

In object-oriented programming, you usually make all of the variables in a class private, as we did previously with width and factor. Then you set the values of these variables either as part of the constructor or using additional set and get functions. This protects these variables from accidental access from outside the class and allows you to add data integrity checks in the set functions to make sure that the data are valid.

We could, of course, have made the TapeMeasure's factor variable public and set it directly.

tp.factor = 2.54;

However, this gives the class no protection from erroneous data such as this.

tp.factor = -50;

So instead, we use accessor functions such as setUnits to make sure that the data values we send the class are valid.

tp.setUnits "c"

Then within the class we would write this accessor function with some error checking.

Likewise, since the TapeMeasure class saves the last measurement it makes, you can always read it back by calling a lastMeasure method.

Passing Arguments by Reference and by Value

By default, all variables are passed into methods by reference. In other words, the original data can be accessed and change within any class method.

Public Sub setTemp(t As Single)
  t = 5              'changes t in the calling program
End Sub

To avoid this happening by accident, you should make a habit of prefixing your arguments with ByVal, which copies the value into the subroutine.

Public Sub setTemp(ByVal t as Single)
       t = 5  'has no affect on calling program
End Sub

Object-Oriented Jargon

Object-oriented programs are often said to have these three major properties.

  • Encapsulation. We hide as much of what is going on inside methods in the object.

  • Polymorphism. Many different objects might have methods with identical names, such as our Measure method. While they may do the same thing, the way each is implemented can vary widely. In addition, there can be several methods within a single object with the same name but different sets of arguments. In VB, a class cannot have multiple methods with the same name but different arguments as in other more polymorphic languages, but related classes can have methods with the same name and arguments that do different things.

  • Inheritance. Objects can inherit properties and methods from other objects, allowing you to build up complex programs from simple base objects. VB6 only supports a subset of inheritance, using interfaces and implementations, as we see in the next chapter. VB.Net is more fully object oriented, and we examine it in Chapters 7 and 8. Nonetheless, even with these limitations, we can use VB6's OO features to write some very sophisticated programs, as you will see shortly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset