Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 28: Object-Oriented Programming with VBA


981


Property errors might occur if the code passes a string when a numeric value is required or when a
property value is less than zero. The following strategies help bulletproof properties and avoid run-
time errors:

l Set default property values if the code passes an inappropriate data type. Use a con-
version routine to correct the value, if possible.
l Use private procedures in the class module to validate data types. These data-
validation routines are often class-specific
l Use error trapping everywhere in the class module, especially on the class’s proper-
ties and methods. The property procedures and methods (the public procedures in the
class) are where most unexpected behaviors occur.

Tip
Keep in mind that a basic principle of using object-oriented programming is encapsulating functionality.
Whenever possible, you should include anything that affects how the class operates in the class module.
Keeping the property validation, method error handling, and other features in the class module makes the class
more portable and reusable.


Encapsulation isn’t well implemented in the clsProduct1 example presented in this section. For
example, the form’s code retrieves the data, and assigns values to the product object’s properties. A
better approach would be to have all the data management performed by the class itself, isolating
the form from the data-management operations. A form using a properly constructed class
shouldn’t have to know which database table contains the product data; instead, the form should
be a strict consumer of the product data.

Recognizing the Benefits of Object-


Oriented Programming


You might be wondering why it’s important to bother with objects. What are the advantages of
Access object-oriented programming? Why complicate things by introducing the complexity of
building and maintaining custom objects when traditional procedural programming techniques
have worked so well in your Access applications?

You’ve already seen how Access’s object-based programming benefits database developers. You do
all the Access data access through Data Access Objects (DAO) or ActiveX Data Objects (ADO) rec-
ognized by the Access database engine. Other built-in Access objects such as forms and controls
include properties you can easily manipulate at design time. As the application runs, these proper-
ties determine the object’s behavior. Creating a form or report requires nothing more than drop-
ping control objects on the form or report’s surface and setting properties to bind the control to
data and establish the control’s appearance.
Free download pdf