Practical Class Design

 < Day Day Up > 



Now that you know what a class is and the mechanics of building one, it’s worth briefly covering some practical tips for building classes.

A Simple Class

It’s quite reasonable to create a class that simply contains only properties and no methods. (See Figure 14-2.)

click to expand
Figure 14-2: You can easily build a simple class in the Visual Basic Editor.

You can create this class by following these steps:

  1. Select Insert, Class Module from the VBA main menu.

  2. Select the new class in the Project Explorer, and change the Name property in the Properties window to Plant.

  3. Enter the following statements into the Edit Window:

    Public CommonName As String
    Public ScientificName As String
    Public Description As String
    Public RetailPrice As Currency
    Public WholesaleCost As Currency
    Public ProductNumber As Long

Extending a Simple Class

One of the advantages of using a class to hold related data is that you can easily extend the class using several different techniques. For example, you can easily add a synonym for an existing property with a pair of property routines like this:

Public Property Get CommonName() As String

CommonName = Name

End Property

Public Property Let CommonName(value As String)

Name = value

End Property

These routines are used to return and modify a public class-level variable, thus allowing the user to manipulate the same value by using two different names.

Another useful technique is to add a method that allows you to initialize all the properties of the class with a single call. Notice that the following routine takes advantage of the Me keyword so that anyone using this method would know which parameter affects which property:

Public Sub Init(Name As String, _
ScientificName As String, _
Description As String, _
RetailPrice As Currency, _
WholesaleCost As Currency, _
ProductNumber As Long)

Me.Name = Name
Me.ScientificName = ScientificName
Me.Description = Description
Me.RetailPrice = RetailPrice
Me.WholesaleCost = WholesaleCost
Me.ProductNumber = ProductNumber

End Sub

A Collection Class

It’s often useful to create a collection class to hold a group of objects. This task is made a lot easier by using the Visual Basic Collection object to store your data. The following code declares a Collection object variable that’s local to the class. When the class is first instantiated, the Collection object is created, and when the object is destroyed, the Collection object will also be destroyed.

Private MyPlants As Collection

Private Sub Class_Initialize()

Set MyPlants = New Collection

End Sub

Private Sub Class_Terminate()

Set MyPlants = Nothing

End Sub

An object is added to the collection using the following code. The code assumes that the object being added has a Name property whose type is String. The routine begins by using the On Error Resume Next statement to disable error trapping. Any errors will simply force Visual Basic to execute the next statement. To detect that an error occurred, the Err object is used.

Public Sub Add(Item As Plant)

Dim i As Long
Dim s As String

On Error Resume Next

i = 0
s = Item.Name
MyPlants.Add Item, s
Do While Err.Number <> 0
i = i + 1
Item.Name = s & "(" & FormatNumber(i, 0) & ")"
Err.Clear
MyPlants.Add Item, Item.Name

Loop

End Sub

The counter i is initially set to zero, and the name of the new object is saved in the temporary variable s. Then the Collection object’s Add method is used to try to add the new object to the Collection object.

If an error occurs in the Add method, the counter i is incremented. A new Name for the object is constructed by using the original name followed by an open parenthesis, the number from the counter i, and a close parenthesis. Then the routine attempts to add the new object to the collection again. If the Add method fails again, the loop is repeated until the name of the object is unique.

An item is removed from the collection by calling the Remove method and specifying either the relative position of the object or the value of the Name property. In either case, the Remove method from the Collection object is used to remove the item from the underlying collection.

Public Sub Remove(key As Variant)

MyPlants.Remove key

End Sub

In the same fashion, the Count method returns the number of items in the collection by calling the underlying Count method associated with the Collection object.

Public Function Count() As Long

Count = MyPlants.Count

End Function

The Clear method is useful if you want to delete all the objects in the collection. This routine just destroys the underlying Collection object and then creates a new instance of the Collection object.

Public Sub Clear()

Set MyPlants = Nothing
Set MyPlants = New Collection

End Sub

The Item method returns a single item from the collection. Like the Remove and Count methods, this item simply calls the Collection object’s Item method.

Public Function Item(key As Variant) As Plant

Set Item = MyPlants.Item(key)

End Function

The following routine is a macro that iterates through the collection class that was just created. The macro begins by creating a new Plants object named MyPlants, which contains a collection of Plant objects. Then the code calls the SampleData method, which simply adds some sample objects to the collection.

Sub Test()

Dim MyPlants As Plants
Dim p As Plant
Dim i As Long

Set MyPlants = New Plants
MyPlants.SampleData

For i = 1 To MyPlants.Count
Set p = MyPlants.Item(i)
MsgBox p.Name

Next i

Set p = Nothing
Set MyPlants = Nothing

End Sub

Next it uses a For Next loop to iterate through each item in the collection. The object variable p is set to the current item from the collection, and the Name property is displayed in a message box.

Notice that the first item in the collection begins with 1, and the number of items in the collection is retrieved from the collection’s Count property.

start sidebar
Where Do I Get My Data?

Classes are an ideal way to hold data from an external source. By holding the data in a collection class, you can allow your program to access the data independently of how the data is physically stored.

This way if you change the way the data is stored, you don’t have to change the way that the data is accessed. By providing a method named LoadData, anyone using the class can load the data from the data source. Then if you migrate the data from a worksheet to an Access database, only the load method will change. The code accessing the collection class won’t change, unless you change the parameters to the LoadData method.

Likewise, you could provide a standard method called SaveData, which would update the data wherever it’s stored. With a little work, you could even make the method intelligent enough so that it updates only the objects that were updated, instead of having to update all the data whether it was updated by the user or not.

end sidebar

A Class with Business Rules

You can also extend a class by adding basic business rules. For example, the following method validates the information in a Plant object. This code merely checks each property in the class with potential error conditions and returns True if no errors are found and False if they are.

Public Function IsValid() As Boolean

If Len(Name) = 0 Then
IsValid = False

ElseIf Len(ScientificName) = 0 Then
IsValid = False

ElseIf WholesaleCost < 0 Then
IsValid = False

ElseIf RetailPrice < WholesaleCost Then
IsValid = False

ElseIf ProductNumber < 0 Then
IsValid = False

Else
IsValid = True

End If

End Function

The IsValid procedure could be modified to return a text error message or even a String array containing a list of errors found within the data.

Another way to detect errors is to use property routines. For instance, you could create a Property Let routine like this one.

Public Property Let RetailPrice(value As Currency)

If value > WholesaleCost Then
MyRetailPrice = value

Else
RaiseEvent PlantError(1, "Retail price lower than the wholesale cost.")

End If

End Property

The class includes a private class-level variable named MyRetailPrice that holds the value for the RetailPrice property. If the new value for RetailPrice is greater than the WholesaleCost, the new retail price will be saved in the MyRetailPrice variable.

However, if someone attempts to set the retail price lower than the wholesale cost, the PlantError event will be fired passing the details of the error to the program that owns the object.

In this chapter, you learned how a class is different from an object. In addition, you learned how to create your own custom classes, including how to define properties, property routines, methods, and events. Some design tips on how to recognize objects, properties, and methods were also discussed. Finally, you learned how to design several different types of classes, including a simple class and a collection class, along with how to extend your classes to include initializing a class and implementing business rules.



 < Day Day Up > 



Microsoft Excel 2003 Programming Inside Out
Microsoft Office Excel 2003 Programming Inside Out (Inside Out (Microsoft))
ISBN: 0735619859
EAN: 2147483647
Year: 2006
Pages: 161

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net