- Rule 2-1: Think in Terms of Interfaces
- Rule 2-2: Use Custom Interfaces
- Rule 2-3: Define Custom Interfaces Separately, Preferably Using IDL
- Rule 2-4: Avoid the Limitations of Class-Based Events with Custom Callbacks
- Rule 2-5: Be Deliberate About Maintaining Compatibility
- Rule 2-6: Choose the Right COM Activation Technique
- Rule 2-7: Beware of Class_Terminate
- Rule 2-8: Model in Terms of Sessions Instead of Entities
- Rule 2-9: Avoid ActiveX EXEs Except for Simple, Small-Scale Needs
Rule 2-4: Avoid the Limitations of Class-Based Events with Custom Callbacks
The notion of events and event handling has been a central feature of VB since its inception. The most common case is graphical user interface (GUI) building, which typically requires the programming of form Load and Unload events, command button Click events, and text box Validate events. But you can also define and raise your own custom, class-based events. For example, the class CConsultant could raise a Changed event whenever one or more data fields in the object are updated:
'** class module CConsultant Option Explicit Implements IEmployee Private sName As String Public Event Changed() '** event definition: Changed Private Property Get IEmployee_Name() As String IEmployee_Name = sName End Sub Private Property Let IEmployee_Name(ByVal sRHS As String) sName = sRHS RaiseEvent Changed '** name was changed, so raise event! End Sub . . .
Any client that holds a reference to a CConsultant object now has the option to handle this event, and thus be notified whenever that employee's data changes:
'** form module denoting client Option Explicit Private WithEvents employee As CConsultant '** client reference Private Sub employee_Changed() '** event handler <update form to reflect change in employee object> End Sub
In essence, events enable an object to call back to its clients, as shown in Figure 2.12.
Figure 2.12 Events are really just a callback mechanism
Unfortunately, VB's class-based event mechanism has a number of limitations. For the client, the WithEvents key word can be applied only to module-level reference variables; arrays, collections, and local variables are not compatible with events. For the class designer, events must be defined in the class that raises them, preventing you from defining a single set of events for reuse across multiple classes. In particular, this means you cannot incorporate events in your custom interfaces, such as IEmployee:
'** class module IEmployee Option Explicit Public Name As String Public Event Changed() '** unfortunately, this doesn't work... Public Sub ReadFromDB(rsCurRecord As ADODB.Recordset) End Sub Public Function IssuePaycheck() As Currency End Function
Although VB accepts this event definition, you'll be unable to raise this event from any of your classes.
The solution to these limitations is to design your own event mechanism based on custom interfaces. Consider once again Figure 2.12. Notice that events represent nothing more than an interface implemented by one or more clients. For example, here is a custom interface IEmployeeEvents that defines the Changed event:
'** class module IEmployeeEvents Option Explicit Public Sub Changed(rEmp As IEmployee) End Sub
The difference is that events are represented as ordinary subroutines; in this case, with an explicit parameter providing a reference back to the object for ease of access. To receive events, the client now implements the appropriate interface, such as IEmployeeEvents:
'** form module denoting client Option Explicit Implements IEmployeeEvents Private Sub IEmployeeEvents_Changed(rEmp As IEmployee) <update form to reflect change in rEmp.Name, etc.> End Sub
But who sets this rClient reference variable?
The client does, by calling the object to set up the callback mechanism. Thus, before any events can occur, the client must first call the object and register itself: 6
rObject.Register Me '** register a reference back to ME, the client
This means the object must expose a Register method. Likewise, the object should expose an Unregister method so that clients can stop receiving events:
rObject.Unregister Me '** unregister ME, the client
Because every object that wishes to raise events must provide a means of client registration, the best approach is to define these methods in a custom interface and to reuse this design across all your event-raising classes. The following interface IRegisterClient summarizes this approach:
'** class module IRegisterClient Option Explicit Public Enum IRegisterClientErrors eIntfNotImplemented = vbObjectError + 8193 eAlreadyRegistered eNotRegistered End Enum Public Sub Register(rClient As Object) End Sub Public Sub Unregister(rClient As Object) End Sub
Now, every class that wishes to raise events simply implements IRegisterClient.
As shown in Figure 2.13, the end result is a pair of custom interfaces, IRegisterClient and IEmployeeEvents. The object implements IRegister Client so that a client can register for events, whereas the client implements IEmployeeEvents so the object can call back when the events occur. For completeness, here's the CConsultant class revised to take advantage of our custom event mechanism:
'** class module CConsultant Option Explicit Implements IRegisterClient Implements IEmployee Private sName As String Private rMyClient As IEmployeeEvents '** ref back to client Private Sub IRegisterClient_Register(rClient As Object) If Not TypeOf rClient Is IEmployeeEvents Then Err.Raise eIntfNotImplemented, ... ElseIf Not rMyClient Is Nothing Then Err.Raise eAlreadyRegistered, ... Else Set rMyClient = rClient End If End Sub Private Sub IRegisterClient_Unregister(rClient As Object) If Not rMyClient Is rClient Then Err.Raise eNotRegistered Else Set rMyClient = Nothing End If End Sub Private Property Get IEmployee_Name() As String IEmployee_Name = sName End Sub Private Property Let IEmployee_Name(ByVal sRHS As String) sName = sRHS On Error Resume Next '** ignore unreachable/problematic clients rMyClient.Changed Me '** name was changed, so raise event! End Sub . . .
Figure 2.13 An event mechanism based on custom interfaces
The first step is to save the client's reference in a private variable (rMyClient) when he registers. Then, whenever we need to raise an event, we simply call the client via this reference. Finally, when the client unregisters, we reset the private variable back to Nothing. Note that the Register and Unregister methods perform error checking to make sure that (1) the client is capable of receiving events, (2) the client is not already registered, and (3) the correct client is being unregistered. Furthermore, to handle multiple clients, also note that the previous approach is easily generalized by replacing rMyClient with a collection of client references.
To complete the example, let's assume on the client side that we have a VB form object that instantiates a number of employee objects (CConsultant, CTechnical, CAdministrative, and so on) and displays them on the screen. The client's first responsibility is to implement the custom IEmployeeEvents interface so it can receive the Changed event:
'** form module denoting client Option Explicit Private colEmployees As New Collection '** collection of object refs Implements IEmployeeEvents Private Sub IEmployeeEvents_Changed(rEmp As IEmployee) <update form to reflect change in rEmp.Name, etc.> End Sub
Here the Changed event is used to drive the updating of the form. Before the client can receive these events however, it must register with each employee object that supports "eventing." In this case we assume the employees are created during the form's Load event based on records from a database:
Private Sub Form_Load() <open DB and retrieve a RS of employee records> Dim rEmp As IEmployee, rObj As IRegisterClient Do While Not rsEmployees.EOF Set rEmp =CreateObject(rsEmployees("ProgID").Value) If TypeOf rEmp Is IRegisterClient Then '** event based Set rObj = rEmp '** switch to register interface... rObj.Register Me '** and register myself to receive events End If rEmp.ReadFromDB rsEmployees colEmployees.Add rEmp rsEmployees.MoveNext Loop <close DB and RS> End Sub
Lastly, the client is also responsible for unregistering when it no longer wishes to receive events. This task is performed during form Unload (i.e., when the form is no longer visible):
Private Sub Form_Unload(Cancel As Integer) Dim rEmp As IEmployee, rObj As IRegisterClient Dim l As Long For l = colEmployees.Count To 1 Step -1 Set rEmp = colEmployees.Item(l) colEmployees.Remove l If TypeOf rEmp Is IRegisterClient Then '** event based Set rObj = rEmp '** switch to register interface... rObj.Unregister Me '** and unregister myself End If Next l End Sub
Note that unregistering is important to break the cyclic reference formed between the client and the object.
Although custom callbacks require more effort to set up than VBs built-in event mechanism, the benefits are many: reusable designs, better callback performance, and more flexibility during implementation. 7 For example, an object with multiple clients can apply a priority-based event notification scheme if desired. In the greater scheme of things, custom callbacks also illustrate the power of using interfaces to design flexible solutions to everyday problems.