I often find the need for states when I am programming. For example, a state might be an edit state or a new state. I see states as something that can be enabled and disabled.
When enabled, the state will produce some actions: For example, an edit state might enable the save button. When this edit state is disabled, this state will disable the save button again, making the save button only pressable when something is edited. When you edit one of the controls, the edit state will be set to true. One way to handle states, is to just code this in the eg. textchanged event. This event will set the save button's enabled property to true. When the save button is pressed, this event (clicked) will set the button's enabled property to false. Althought the wanted result can be achieved this way, I find this rather "ugly": many actions in many different events, not knowing if an action belongs to a state or something else. I have tried to solve this using a State Class:
VB .Net Code:
Public Class State
Private m_Enable As Boolean = False
Public Property Enable() As Boolean
Get
Return m_Enable
End Get
Set(ByVal Value As Boolean)
' If value is still in the same state, then exit
If m_Enable = Value Then
Exit Property
Else
m_Enable = Value
End If
' State has change: raise the proper event
If m_Enable = True Then
RaiseEvent Enabled(Enable)
Else
RaiseEvent Disabled(Enable)
End If
End Set
End Property
Public Event Enabled(ByVal sender As Object)
Public Event Disabled(ByVal sender As Object)
End Class
Example:
Private WithEvents editState As State = New State
Private Sub editState_Enabled(ByVal sender As Object) Handles editState.Enabled
' Enable the Save Button: btnSave.Enabled = true
End Sub
Private Sub editState_Disabled(ByVal sender As Object) Handles editState.Disabled
' Disable the Save Button: btnSave.Enabled = false
End Sub
Please give any feedback about above: Do you find this need to? Do you solve this in a different way? Do you think this is a bit of "over-enginering"? Etc...
Gr,
Michel van den Berg (aka BlueCell and Promontis)