November 03, 2008

Implement an IsSaved Property


Implement an IsSaved (or IsDirty) Property

I often find this technique very useful, but it takes a little extra work when you're creating your object classes. On balance, despite this up front investment of time, it saves a good deal of programming time by making it easy to determining when an object has changed and therefore needs to be saved.

To implement an IsSaved or IsDirty property, each Property Let procedure of a particular object must contain a line of code to determine if the value to be assigned to the property is different than its current value (which should be stored in a private member variable). If it is different, then the private member variable that represents the IsSaved property is set to False. For example:

Property Let CustStreetAddr(sVal as String)
If msCustStreetAddr <> sVal Then
msCustStreetAddr = sVal
mbIsSaved = False
End If
End Property

(Of course, you can also implement this the other way round by having an IsDirty property that returns True when the object needs to be saved.)

Back at the client end you can check to see if the object needs saving quickly and easily as follows:

If Not myObject.IsSaved Then
SaveTheObject
End If

On the server object, this is implemented as a simple Property Get procedure:

Property Get IsSaved() As Boolean
IsSaved = mbIsSaved
End Property

Another neat addition to this is to define an object event called something like ObjectChanged. Then the event can be fired whenever some attribute of the object changes:

Property Let CustStreetAddr(sVal As String)
If msCustStreetAddr <> sVal Then
msCustStreetAddr = sVal
mbIsSaved = False
RaiseEvent ObjectChanged()
End If
End Property

On the client form, you can then implement an event handler for the ObjectChanged event that enables the Save button when the object needs to be saved:

Sub MyObject_ObjectChanged()
cmdSave.Enabled = Not myObject.IsSaved
End Sub

This code enables the Save button when the object is not saved and disables the button when the object has been changed.

I should add a major qualification to this tip: don't update your object property based on the Change event handler of a text box. The Change event is fired for each keystroke that the text box receives. Therefore typing a word like "Stupid" into the text box will fire off 6 Change events - and the final result is that the text box could contain the same word that it originally started with, so that in fact its contents haven't changed at all despite the firing of six unnecessary events.

0 comments:

Post a Comment

 

Copyright 2008 All Rights Reserved | Blogger Template by Computer Science and Computer Tips