R E V E R S I B L E
a: capable of going through a series of actions
such as changes) either backward or forward)
Merriam-Webster dictionary
The ability to undo and then, likely, redo actions is constituent and multi-plugged for most applications. Besides traditional usage Undo-Redo may replace tedious confirmation ("are you sure"), run wizards, and explore tree structures.
Let's knock ourselves out to implement reversible in a project, deserving just two words of others: using Reversible;
.
Next snippets of C#, degraded for emphasis, feature some basics:
♟️ Model a popular subject (chess)
class Chess<T>
{
bool _blackOn;
virtual T _move { get; set; }
T Move {
get => _move;
set {
Validate(value);
_move = value; _blackOn ^= true;
Notify();
}
}
virtual void Validate(T value) { ... } // check notation and validate move here
virtual void Notify() => Console.WriteLine($"{(_blackOn ? "black" : "white")}: {Move}");
}
⏮️ Upgrade it with Undo()
using Reversible;
public class IndulgentChess<T> : Chess<T>, IUndoable
{
IUndoable<T> _backup = UndoOnly.Empty<T>();
override T _move { get => _backup.Item; set => _backup.Item = value; }
void Undo(int steps = 1) => _backup.Undo(steps);
}
🍿 Present the usage
var game = new IndulgentChess<string> { Move = "d4" }; // white begin ...
game.Move = "Nf6"; // Indian Defence
game.Move = "c4";
game.Move = "0-1"; // a world champion would resign the game ...
game.Undo(); // ... but not you
game.Move("e6");
// ...
ℹ️ Game sample inspired by Champions Chess Tour 2022w
If these "antipasti" have aroused your appetite to redo, the Handbook will share recipes of further features and use cases backed by Q&A.
However ... isn't that all an over-engineering of the indexed element? 🔨 You decide, while Rationale along with Posers & Decisions tries to advocate our efforts.
🔨For instance, Moves[i]
for current value, i--
for undo and i++
for redo.
UndoOnly
for the snippet above is too trivial to deserve your look into the repository but not the whole project, which you may follow in Developer book, contribute to it, or rework for your own purposes.
___________
🔚 ... but README+