Reversibility

time to read 2 min | 202 words

No, I am not talking about Jeremey Miller's reversibility. I am talking about another matter all together. I have an API that perform an operation. The problem is that based on the result of this operation, I may need to cancel that operation.

The main issue here is that in order to reverse this operation, I need to expose too much information to the client, which I rather not do. Let us take the following interface as an example:

public interface IActionStack
{
	ActionSpec Pop();
	void Push(ActionSpec action);
}

The code I would like to write is something like this:

while(true)
{
	var action = actionStack.Pop();
	if (action.ExecuteAt >= DateTime.Now )
		action.Execute();
	else
		actionStack.Push(action);
	Thread.Sleep(1000);
}

But there is meaning to the order of items in the stack, so I can just reorder it. Peek or PushFirst are not applicable here. What I came up with was:

public interface IActionStack 
{ 
	ActionSpec Pop(); 
	ActionSpec ReversiblePop(out System.Action reversePop); 
	void Push(ActionSpec action); 
}

And the client code is:

while(true)
{
	System.Action reverse;
	var action = actionStack.ReversiblePop(out reverse);
	if (action.ExecuteAt >= DateTime.Now )
		action.Execute();
	else
		reverse();
	Thread.Sleep(1000);
}

Thoughts?