Resource Acquisition at Initialisation

If a resource must be both acquired and released in the scope of a procedure, then tie the acquisition and release to the lifetime of an object.


For example.  Suppose we need to switch the cursor to an hourglass and back for an event procedure...


Private Sub Form_Click()

    Me.MousePointer = vbHourglass



    'Do work

    Call LongRunningSub

    If SomeEarlyExitCondition Then

        Me.MousePointer = vbDefault

        Exit Sub

    End If



    Me.MousePointer = vbDefault

End Sub


There is scope for error, even in this simple example, because for every early exit point the programmer must REMEMBER to set the MousePointer back to the correct state.  Every time we rely on the programmer to remember; things can go wrong.


If we package the manipulation of the mouse pointer into a separate class module...


Class CWaitCursor


Option Explicit



Private Sub Class_Initialize()

    Screen.MousePointer = vbHourglass

End Sub



Private Sub Class_Terminate()

    Screen.MousePointer = vbDefault

End Sub


...and modify Form_Click...


Private Sub Form_Click()

    Dim Wait As CWaitCursor

    Set Wait = New CWaitCursor    '[1] Causes the hourglass cursor to appear



    'Do work

    Call LongRunningSub

    If SomeEarlyExitCondition Then

        Exit Sub                 
'[2]

    End If



End Sub                          
'[2]


The line (marked [1]) causes the hourglass to appear.  This happens because the Initialize event of the class sets the hourglass.  Hence the name Resource (the hourglass) Acquisition (getting it) At Initialization (when the class object is initialized).  The other side of the coin is unspoken.  It is the release of the resource in the Terminate event, when the object is 'de-initialized' i.e. when it is destroyed.


The hourglass will go away when the variable Wait goes out of scope (or is explicitly set to Nothing.) Now it does not matter how many early exit points the programmer adds.  There is never any need to worry about setting the hourglass cursor back.  It just happens automatically. In the example above at the lines marked [2]


If we need to exercise more control we can.  We can defer the line that creates the CWaitCursor object if we don't always want the hourglass.  We can go back to the default by setting Wait to Nothing.


This example relies on the VB6 interpretation of object lifetime.  It does not work in .NET because object lifetime is managed differently in the .NET environment.

There is a code sample available from the articles/downloads page.

Copyright 2002-15 by Dynamisys Ltd