Capstone C: the task and the model

The third capstone is a to-do list with a presenter, undo and JSON persistence. Its core is a small state machine: a task is new, then active, then done, and it can go back to active. Everything the app promises about a task is a method on that machine, and everything the app refuses is an exception with a message a status line can show.

The three states

TaskState has three values. New is a task the user has not begun, Active one in progress, Done one finished. A fourth state for archived tasks is a different application; the capstone keeps three because three is what its screens need.

The item exposes the transitions as verbs rather than a settable state: Start, Complete and Reopen. A public setter would let a caller put a task in any state and would make the rules unenforceable. The state property has a private setter, and the only public way to change it is a verb.

Transitions that are not allowed

Three transitions are allowed: new to active, active to done, and done back to active. Everything else throws InvalidOperationException with a message that names the state the task is in. That exception is the rule; a caller that cannot produce an invalid transition does not need to catch it, and a presenter that can, does.

The check is a switch over the pair of the current and the next state, written out rather than computed. It is three lines and it is readable at a glance, which is what a rule that a support engineer will read at midnight should be.

The list and its rules

The list owns the ids and the rules a single task cannot enforce. An id is generated as T-1, T-2, and it is never reused in a run: a removed task leaves a gap, which is the right behaviour for an id that a log may mention.

The model in a program that runs

The model with every rule exercised: two adds, a start, a complete, a reopen, a duplicate, an invalid transition, a blank title, a long title and a remove. It was built and run in the container:

using System; using System.Collections.Generic; Console.WriteLine("a task list and its states"); var list = new TaskList(); var first = list.Add("Write the course"); var second = list.Add("Review lesson 077"); Console.WriteLine($"added {first.Id} '{first.Title}' ({first.State})"); Console.WriteLine($"added {second.Id} '{second.Title}' ({second.State})"); first.Start(); Console.WriteLine($"{first.Id} start: {first.State}"); first.Complete(); Console.WriteLine($"{first.Id} complete: {first.State}"); Console.WriteLine($"counts: {list.Count} tasks, {list.ActiveCount} active, {list.DoneCount} done"); first.Reopen(); Console.WriteLine($"{first.Id} reopen: {first.State}"); first.Complete(); Console.WriteLine($"done after completing again: {string.Join(", ", list.Done)}"); Try("duplicate", () => list.Add("write the course")); Try("new to done", () => second.Complete()); Try("blank", () => list.Add(" ")); Try("too long", () => list.Add(new string('x', 81))); list.Remove(second.Id); Console.WriteLine($"remove {second.Id}: {list.Count} left"); void Try(string label, Action action) { try { action(); Console.WriteLine($"{label}: no error"); } catch (Exception error) when (error is InvalidOperationException or ArgumentException) { Console.WriteLine($"{label}: {error.Message}"); } } 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; private set; } public TaskState State { get; private set; } public void Start() => Move(TaskState.Active, "start"); public void Complete() => Move(TaskState.Done, "complete"); public void Reopen() => Move(TaskState.Active, "reopen"); public void Rename(string title) { TaskList.CheckTitle(title); Title = title; } internal void Restore(TaskState state) => State = state; private void Move(TaskState next, string verb) { var allowed = (State, next) switch { (TaskState.New, TaskState.Active) => true, (TaskState.Active, TaskState.Done) => true, (TaskState.Done, TaskState.Active) => true, _ => false, }; if (!allowed) { throw new InvalidOperationException($"Cannot {verb} a task in state {State}."); } State = next; } } 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 int ActiveCount => _items.FindAll(item => item.State == TaskState.Active).Count; public int DoneCount => _items.FindAll(item => item.State == TaskState.Done).Count; public IEnumerable<string> Done { get { foreach (var item in _items) { if (item.State == TaskState.Done) { yield return item.Title; } } } } public TodoItem Add(string title) { CheckTitle(title); foreach (var item in _items) { if (string.Equals(item.Title, title.Trim(), StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException($"Cannot add '{title.Trim()}': the title is already used."); } } var added = new TodoItem($"T-{_next++}", title.Trim(), 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); internal static void CheckTitle(string title) { var trimmed = title.Trim(); if (trimmed.Length == 0) { throw new ArgumentException("A title must not be empty.", nameof(title)); } if (trimmed.Length > 80) { throw new ArgumentException("A title is limited to 80 characters.", nameof(title)); } } }

dotnet run

a task list and its states
added T-1 'Write the course' (New)
added T-2 'Review lesson 077' (New)
T-1 start: Active
T-1 complete: Done
counts: 2 tasks, 0 active, 1 done
T-1 reopen: Active
done after completing again: Write the course
duplicate: Cannot add 'write the course': the title is already used.
new to done: Cannot complete a task in state New.
blank: A title must not be empty. (Parameter 'title')
too long: A title is limited to 80 characters. (Parameter 'title')
remove T-2: 1 left

The output is the real run. The ids were generated in order, the counts followed the states, and the reopen made the task active again before it was completed a second time. The four failures are the four rules, each with the message a status line would show; the duplicate one names the title in the trimmed form the comparison used, which is why write the course is lower case in the message.

Exercises

  1. Add a Block state and a Block verb from active, then extend the run with a blocked task.
  2. Add a Move that reorders two items by id and print the order after it.
  3. Explain why the id is not reused and what a log of completed tasks would lose if it were.

Questions

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

  1. How many states does a task have in this capstone?

    Answer

    Three: new, active and done

    Archived would be a different application.

  2. Why are the transitions methods and not a state property?

    Answer

    A setter would let a caller break the rules

    Start, Complete and Reopen are the only public changes.

  3. Which transition is allowed?

    Answer

    Done to active

    Reopen is the way back from done.

  4. What did the run print for a new-to-done attempt?

    Answer

    Cannot complete a task in state New.

    The switch rejects the pair.

  5. Why is the duplicate title compared case-insensitively?

    Answer

    Write and write are the same title for the user

    The rule is about the title the user sees.

  6. What is the title limit?

    Answer

    80 characters

    The run prints the message for 81 characters.

  7. How are the done and active counts computed?

    Answer

    From the items on each call

    There is no second copy to keep in step.

  8. What happens to an id when its task is removed?

    Answer

    It leaves a gap and is not reused

    A log may mention the id after the task is gone.

  9. Which exception does a blank title produce?

    Answer

    ArgumentException with the parameter name

    The run shows (Parameter 'title').

  10. What did the counts show after the first complete?

    Answer

    2 tasks, 0 active, 1 done

    T-1 was done, T-2 was still new.

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