Capstone C: the presenter and undo

The to-do presenter is the third one in the course, and it adds the feature the notes app did not need: every command is undoable. The design is the command stack of lesson 056, with the commands built around the state machine of lesson 077, and the whole thing runs against a fake view.

The view interface

The view is a list of strings, a selection, a status line, two booleans for the menu, and the two questions a to-do screen asks. The presenter formats the items, so the view never learns what a state is:

internal interface ITodoView { void ShowItems(IReadOnlyList<string> items); int SelectedIndex { get; } string Status { set; } bool CanUndo { set; } bool CanRedo { set; } void ClearSelection(); string? AskTitle(); bool ConfirmRemove(); event EventHandler? AddRequested; event EventHandler? CompleteRequested; event EventHandler? RemoveRequested; event EventHandler? UndoRequested; event EventHandler? RedoRequested; }

ClearSelection is there because a removal can leave the selected index past the end of the list. The presenter checks it after every refresh rather than in the remove handler alone: an undo can also shorten the list, and the rule belongs in one place.

Three commands

Each command stores what its inverse needs. The add command keeps the item it created, so a redo does not create a second one; the complete command keeps the state the item had; the remove command keeps the item and its index, so the undo puts it back where it was.

internal interface IUndoable { void Do(); void Undo(); } internal sealed class AddTask : IUndoable { private readonly TaskList _list; private readonly string _title; private TodoItem? _item; public AddTask(TaskList list, string title) { _list = list; _title = title; } public void Do() { _item ??= _list.Add(_title); if (_list.Find(_item.Id) is null) { _list.Insert(_list.Count, _item); } } public void Undo() { if (_item is not null) { _list.Remove(_item.Id); } } } internal sealed class CompleteTask : IUndoable { private readonly TodoItem _item; private TaskState _before; public CompleteTask(TodoItem item) => _item = item; public void Do() { _before = _item.State; if (_item.State == TaskState.New) { _item.Start(); } _item.Complete(); } public void Undo() => _item.Restore(_before); } internal sealed class RemoveTask : IUndoable { private readonly TaskList _list; private readonly TodoItem _item; private readonly int _index; public RemoveTask(TaskList list, TodoItem item) { _list = list; _item = item; _index = list.IndexOf(item.Id); } public void Do() => _list.RemoveAt(_index); public void Undo() => _list.Insert(_index, _item); }

Two details are lessons in themselves. CompleteTask.Do starts a task that is still new before it completes it, which is a product rule: completing a task the user never started is allowed and means the same as starting and finishing it. And RemoveTask captures the index at construction, not at undo, because the list may have changed between the two.

Undo, redo and the selection

The two stacks are exactly the ones of lesson 056: a command is pushed on undo after it succeeds, redo moves it back, and a new command clears redo. What is new is the status line and the two booleans the menu reads. Run returns a bool so the handler knows whether to write a success message or leave the error the catch wrote.

A failed command is not pushed. That is the reason Run catches the two model exceptions around Do: a task that cannot be completed, or a title that is a duplicate, must not become an undo step that would restore nothing.

The presenter in a program that runs

The whole program: the fake view, the presenter, the commands and a smaller copy of the model. It walks through add, complete, undo, redo, remove, undo, a new task that clears redo, and it prints the list after every step. It was built and run in the container:

using System; using System.Collections.Generic; Console.WriteLine("the to-do presenter with undo"); var view = new FakeView(); var presenter = new TodoPresenter(new TaskList(), view); view.NextTitle = "Write"; view.RaiseAdd(); view.NextTitle = "Review"; view.RaiseAdd(); Print("add two", view); view.SelectedIndex = 1; view.RaiseComplete(); Print("complete the second", view); view.RaiseUndo(); Print("undo", view); view.RaiseRedo(); Print("redo", view); view.SelectedIndex = 0; view.ConfirmRemoveAnswer = true; view.RaiseRemove(); Print("remove the first", view); view.RaiseUndo(); Print("undo the remove", view); view.NextTitle = "Ship it"; view.RaiseAdd(); Console.WriteLine($"can undo: {view.CanUndo}, can redo: {view.CanRedo}"); Console.WriteLine($"status: {view.Status}"); Print("after a new command", view); void Print(string label, FakeView fake) { Console.WriteLine($"{label}: {string.Join(", ", fake.Items)}"); } internal interface ITodoView { void ShowItems(IReadOnlyList<string> items); int SelectedIndex { get; } string Status { set; } bool CanUndo { set; } bool CanRedo { set; } void ClearSelection(); string? AskTitle(); bool ConfirmRemove(); event EventHandler? AddRequested; event EventHandler? CompleteRequested; event EventHandler? RemoveRequested; event EventHandler? UndoRequested; event EventHandler? RedoRequested; } internal sealed class FakeView : ITodoView { public IReadOnlyList<string> Items { get; private set; } = Array.Empty<string>(); public int SelectedIndex { get; set; } public string Status { get; set; } = string.Empty; public bool CanUndo { get; set; } public bool CanRedo { get; set; } public string? NextTitle { get; set; } public bool ConfirmRemoveAnswer { get; set; } public void ShowItems(IReadOnlyList<string> items) => Items = items; public void ClearSelection() => SelectedIndex = -1; public string? AskTitle() => NextTitle; public bool ConfirmRemove() => ConfirmRemoveAnswer; public void RaiseAdd() => AddRequested?.Invoke(this, EventArgs.Empty); public void RaiseComplete() => CompleteRequested?.Invoke(this, EventArgs.Empty); public void RaiseRemove() => RemoveRequested?.Invoke(this, EventArgs.Empty); public void RaiseUndo() => UndoRequested?.Invoke(this, EventArgs.Empty); public void RaiseRedo() => RedoRequested?.Invoke(this, EventArgs.Empty); public event EventHandler? AddRequested; public event EventHandler? CompleteRequested; public event EventHandler? RemoveRequested; public event EventHandler? UndoRequested; public event EventHandler? RedoRequested; } internal interface IUndoable { void Do(); void Undo(); } internal sealed class TodoPresenter { private readonly TaskList _list; private readonly ITodoView _view; private readonly Stack<IUndoable> _undo = new(); private readonly Stack<IUndoable> _redo = new(); public TodoPresenter(TaskList list, ITodoView view) { _list = list; _view = view; view.AddRequested += OnAdd; view.CompleteRequested += OnComplete; view.RemoveRequested += OnRemove; view.UndoRequested += (sender, e) => Undo(); view.RedoRequested += (sender, e) => Redo(); Refresh(); } private void OnAdd(object? sender, EventArgs e) { var title = _view.AskTitle(); if (string.IsNullOrWhiteSpace(title)) { _view.Status = "A title is required."; return; } if (Run(new AddTask(_list, title))) { _view.Status = $"Added '{title.Trim()}'."; } } private void OnComplete(object? sender, EventArgs e) { var item = Selected(); if (item is null) { return; } if (Run(new CompleteTask(item))) { _view.Status = $"Completed '{item.Title}'."; } } private void OnRemove(object? sender, EventArgs e) { var item = Selected(); if (item is null) { return; } if (!_view.ConfirmRemove()) { _view.Status = "Remove cancelled."; return; } if (Run(new RemoveTask(_list, item))) { _view.Status = $"Removed '{item.Title}'."; } } private TodoItem? Selected() { var index = _view.SelectedIndex; if (index < 0 || index >= _list.Count) { _view.Status = "Select a task first."; return null; } return _list.Items[index]; } private bool Run(IUndoable command) { try { command.Do(); _undo.Push(command); _redo.Clear(); Refresh(); return true; } catch (Exception error) when (error is InvalidOperationException or ArgumentException) { _view.Status = error.Message; return false; } } private void Undo() { if (_undo.Count == 0) { return; } var command = _undo.Pop(); command.Undo(); _redo.Push(command); Refresh(); _view.Status = "Undo."; } private void Redo() { if (_redo.Count == 0) { return; } var command = _redo.Pop(); command.Do(); _undo.Push(command); Refresh(); _view.Status = "Redo."; } private void Refresh() { var items = new List<string>(); foreach (var item in _list.Items) { items.Add($"{item.Id} {item.Title} [{item.State}]"); } _view.ShowItems(items); _view.CanUndo = _undo.Count > 0; _view.CanRedo = _redo.Count > 0; if (_view.SelectedIndex >= _list.Count) { _view.ClearSelection(); } } } internal sealed class AddTask : IUndoable { private readonly TaskList _list; private readonly string _title; private TodoItem? _item; public AddTask(TaskList list, string title) { _list = list; _title = title; } public void Do() { _item ??= _list.Add(_title); if (_list.Find(_item.Id) is null) { _list.Insert(_list.Count, _item); } } public void Undo() { if (_item is not null) { _list.Remove(_item.Id); } } } internal sealed class CompleteTask : IUndoable { private readonly TodoItem _item; private TaskState _before; public CompleteTask(TodoItem item) => _item = item; public void Do() { _before = _item.State; if (_item.State == TaskState.New) { _item.Start(); } _item.Complete(); } public void Undo() => _item.Restore(_before); } internal sealed class RemoveTask : IUndoable { private readonly TaskList _list; private readonly TodoItem _item; private readonly int _index; public RemoveTask(TaskList list, TodoItem item) { _list = list; _item = item; _index = list.IndexOf(item.Id); } public void Do() => _list.RemoveAt(_index); public void Undo() => _list.Insert(_index, _item); } internal enum TaskState { New, Active, Done, } internal sealed class TodoItem { internal TodoItem(string id, string title, TaskState state) { Id = id; Title = title; State = state; } public string Id { get; } public string Title { get; } public TaskState State { get; private set; } public void Start() { if (State != TaskState.New) { throw new InvalidOperationException($"Cannot start a task in state {State}."); } State = TaskState.Active; } public void Complete() { if (State != TaskState.Active) { throw new InvalidOperationException($"Cannot complete a task in state {State}."); } State = TaskState.Done; } internal void Restore(TaskState state) => State = state; } internal sealed class TaskList { private readonly List<TodoItem> _items = new(); private int _next = 1; public IReadOnlyList<TodoItem> Items => _items; public int Count => _items.Count; public TodoItem Add(string title) { var trimmed = title.Trim(); if (trimmed.Length == 0) { throw new ArgumentException("A title must not be empty.", nameof(title)); } var added = new TodoItem($"T-{_next++}", trimmed, TaskState.New); _items.Add(added); return added; } public TodoItem? Find(string id) => _items.Find(item => item.Id == id); public bool Remove(string id) { var item = Find(id); return item is not null && _items.Remove(item); } public int IndexOf(string id) => _items.FindIndex(item => item.Id == id); public void Insert(int index, TodoItem item) => _items.Insert(Math.Clamp(index, 0, _items.Count), item); public void RemoveAt(int index) => _items.RemoveAt(index); }

dotnet run

the to-do presenter with undo
add two: T-1 Write [New], T-2 Review [New]
complete the second: T-1 Write [New], T-2 Review [Done]
undo: T-1 Write [New], T-2 Review [New]
redo: T-1 Write [New], T-2 Review [Done]
remove the first: T-2 Review [Done]
undo the remove: T-1 Write [New], T-2 Review [Done]
can undo: True, can redo: False
status: Added 'Ship it'.
after a new command: T-1 Write [New], T-2 Review [Done], T-3 Ship it [New]

The output is the real run. Complete moved the second task through active to done, undo put it back to new, redo returned it to done. The removal of the first task was undone into its original position, before the done one. The new task cleared the redo stack, which is why can redo is false and the status line is the add message rather than anything about the old history.

Exercises

  1. Add a RenameTask command and a RenameRequested event, and extend the run with one rename and its undo.
  2. Make CompleteTask refuse a task that is new and add a StartRequested event; compare the two designs in a sentence.
  3. Print the number of undo and redo steps in the fake view and check it against the output above.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does each command store?

    Answer

    What its inverse needs: the item, the state or the index

    The commands are small and specific.

  2. Why does AddTask keep the item it created?

    Answer

    So a redo reinserts the same item instead of creating another

    The item carries its id and state.

  3. What does CompleteTask do to a new task?

    Answer

    Starts it and then completes it

    Completing a task that was never started is allowed.

  4. What does RemoveTask capture?

    Answer

    The item and its index

    The undo puts the item back where it was.

  5. When is a command pushed on the undo stack?

    Answer

    After Do succeeds

    A failed command must not become an undo step.

  6. What did undo do after completing the second task?

    Answer

    Returned it to New

    The before state was New, and the undo restored it.

  7. What did the new task do to redo?

    Answer

    Cleared it

    The run shows can redo False.

  8. When is the selection checked against the list length?

    Answer

    After every refresh

    An undo can shorten the list too.

  9. What does the presenter show in the list?

    Answer

    The id, the title and the state as formatted strings

    The view does not need to know TaskState.

  10. Why does Run return a bool?

    Answer

    The handler writes a success status only when the command worked

    The catch writes the failure status instead.

Every listing on this page is plain .NET code with no window in it: it was built and run with the .NET SDK 10.0.303 on Alpine Linux 3.24.3 (x86_64) in a Docker container, and the output printed below the program is that run. The WinForms pages of this course are built for net10.0-windows against Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed and never run on Linux: WinForms needs Windows.

Article author: Arthur Isaev

Banner image