Using Exceptions and Ensuring Invariants
Design and Architecture
1
Posts
1
Posters
4
Views
1
Watching
-
I think it's important that if a method throws an exception, the object from which the exception is thrown is left in a consistent state, that is its invariants are left intact. This can be challenging, though. Consider a method that sets a value:
public void SetValue(int value)
{
// Range checking omitted...this.value = value; // Do some operation based on the new value that could // possibly throw an exception. // If an exception is thrown, we need to revert 'value' // back to its previous value.
}
My current approach to this is to postpone updating an object's values until an operation has completed successfully. This means possibly caching temp values as you perform a series of operations, each of which may throw an exception. Once everything has completed, we can update the object's values. So instead of the above with the assignment to 'value' taking place at the beginning method, we move it down to the bottom. Thoughts?