Several times we need to be able to revert the data the user is inserting to a previous state (cancel data update). In order to keep DRY and for the sake of separation of concerns I thought about a way of just allowing that.
public class RevertableObject<T> : ViewModelBase //implements INotifyPropertyChanged
where T:class, ICloneable
{
public RevertableObject(T initialValue)
{
Value = initialValue;
Value = initialValue.Clone() as T;
}
private T _oldValue;
private T _currentValue;
public T Value
{
get { return _currentValue; }
private set
{
_oldValue = _currentValue;
_currentValue = value;
OnPropertyChanged();
}
}
public void Revert()
{
Value = _oldValue;
}
}
Some drawbacks of this solution are, but are not limited to:
- Dependency on the interface
ICloneable
which does not have a way of knowing the cloning algorithm being used (member clone vs deep clone) - It only allows one object to be reverted once.
Any insights of better alternatives? Is this code acceptable?