views:

512

answers:

3

If I have an Address object which implements IEditableObject, I might have EndEdit implementation like this:

public void EndEdit()
{
    // BeginEdit would set _editInProgress and update *Editing fields;
    if (_editInProgress)
    {
        _line1 = _line1Editing;
        _line2 = _line2Editing;
        _city = _cityEditing;
        _state = _stateEditing;
        _postalCode = _postalCodeEditing;
        _editInProgress = false;
    }
}

If there is an exception updating *state, for example, then all 5 properties should reset. This atomic update issue probably isn't limited to EndEdit.

A: 

(for some reason the commenting function isn't there at the moment)

Why would setting a field ever throw an exception?

Kent Boogaart
what if they were not simple fields like strings, but complex objects?
Jiho Han
+1  A: 

First off, Kent is correct in wondering why setting a field would throw an exception.
Ignoring that question; you could just use a simple:

try {
  //do stuff
}
catch (Exception ex) {
  //reset

  //rethrow exception
  throw;
}

The complications come in with regards to what constitutes the reset value for each field?

  • The last value
  • A default value
  • Some token value denoting an invalid state
  • A mix of the above

If you need to "reset" to the last value then you'll likely want some way to easily store the object state before doing something to it, along with the ability to easily restore that state should something go wrong. Check out the Momento Pattern on a nifty way to deal with that problem.

akmad
"Reset" would mean the last value. Why would we reset to default values, ever? I'm not sure about the invalid tokens. I'll definitely check out Memento pattern regardless - thanks!
Jiho Han
A: 

I don't use fields for storing values. Instead I use a hash table that the properties can read and write. This gives me a really simple design.

Friend Sub BeginEdit()
    m_Backup = New Dictionary(Of String, Object)(m_DataPoints, StringComparer.OrdinalIgnoreCase)
End Sub

Friend Sub CancelEdit()
    If m_Backup IsNot Nothing Then m_DataPoints = m_Backup
End Sub

Friend Sub EndEdit()
    m_Backup = Nothing
End Sub
Jonathan Allen