Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 28: Object-Oriented Programming with VBA


995


Public Property Get SupplierName() As String
Dim varTemp As Variant
If m_SupplierID <= 0 Then
SupplierName = vbNullString
Exit Property
End If
varTemp = DLookup(“CompanyName”, “Suppliers”, _
“SupplierID = “ & m_SupplierID)
If Not IsNull(varTemp) Then
SupplierName = CStr(varTemp)
Else
SupplierName = vbNullString
End If
End Property

The Property Get uses DLookup to retrieve the CompanyName from the Suppliers table
that matches the m_SupplierID property variable. The property variable is first checked to make
sure its value is greater than zero, and the property ends if this condition is not met.


The SupplierName property is an example of how a class module can be enhanced by introduc-
ing new properties — read-only, write-only, or read/write — that provide functionality not other-
wise available. Again, the consumer of the class doesn’t have to know anything about the
underlying data structures, and all the data management is handled through the class module.


Adding a new method to the product class


In the “Recognizing the Benefits of Object-Oriented Programming” section, earlier in this chapter, I
discussed some of the advantages of encapsulation. Another major advantage of encapsulation is
that, because all data operations required by the entity are contained within the class, it’s quite easy
to update business logic.


Assume that the hypothetical SellProduct method (introduced in the “Following the rules”
sidebar, earlier in this chapter) has to be updated to accommodate a new sales tax. Whichever
technique you use to update the method, the end result is the same. Because the method is an inte-
gral part of the class, there is only one update needed to update all uses of the SellProduct
method in the application.


The previous section dealt with an update to the ProductID property. In the new ProductID
Property Let, the property variable was assigned –1 when it appeared that the product was a
new product. Here’s how the SaveProduct method would handle the various values of the m_
ProductID variable:


Public Function SaveProduct() As Boolean
Dim db As DAO.Database
Dim strSQL As String
On Error GoTo HandleError
Set db = CurrentDb()
If m_ProductID > 0 Then
‘Update existing record:
Free download pdf