Skip to content

Assemble the Task Tracker

The Course
•
20 min study

Here's the complete application. Each file is a tab. Read Program.cs first, since it's short, then follow Commands.cs into Tracker.cs. Press Run, and compare the output with the brief.

Task tracker C#
#nullable enable using TaskTracker; var commands = new Commands(new Tracker(), new SystemClock()); string? line; while ((line = Console.ReadLine()) is not null) { foreach (string output in commands.Execute(line)) { Console.WriteLine(output); } } #nullable enable using System.Globalization; namespace TaskTracker; // Turns one line of text into output lines, so it can be checked without a console. public class Commands { private readonly Tracker tracker; private IClock clock; public Commands(Tracker tracker, IClock clock) { this.tracker = tracker; this.clock = clock; } public IReadOnlyList<string> Execute(string line) { string[] parts = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (parts.Length == 0) { return Array.Empty<string>(); } string argument = parts.Length == 2 ? parts[1] : ""; return parts[0] switch { "add" => Add(argument), "done" => WithId(argument, "Completed", tracker.Complete), "remove" => WithId(argument, "Removed", tracker.Remove), "list" => List(), "report" => BuildReport(), "save" => Store(argument, tracker.Save, "Saved"), "load" => Store(argument, tracker.Load, "Loaded"), "today" => SetToday(argument), _ => Error($"unknown command {parts[0]}"), }; } private static string[] Error(string message) => new[] { $"Error: {message}" }; private static bool TryParseDate(string text, out DateOnly date) { return DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date); } private string[] Add(string argument) { string[] fields = argument.Split(' ', 3, StringSplitOptions.TrimEntries); if (fields.Length != 3) { return Error("usage: add <priority> <yyyy-MM-dd> <title>"); } if (!Enum.TryParse(fields[0], ignoreCase: true, out Priority priority) || !Enum.IsDefined(priority)) { return Error($"unknown priority {fields[0]}"); } if (!TryParseDate(fields[1], out DateOnly due)) { return Error($"bad date {fields[1]}"); } return tracker.Add(fields[2], priority, due) switch { Ok<TaskItem> ok => new[] { $"Added {ok.Value.Id}: {ok.Value.Title}" }, Fail<TaskItem> fail => Error(fail.Error), _ => throw new InvalidOperationException("unknown result"), }; } private static string[] WithId(string argument, string verb, Func<int, Result<TaskItem>> action) { if (!int.TryParse(argument, out int id)) { return Error($"bad id {argument}"); } return action(id) switch { Ok<TaskItem> ok => new[] { $"{verb} {ok.Value.Id}: {ok.Value.Title}" }, Fail<TaskItem> fail => Error(fail.Error), _ => throw new InvalidOperationException("unknown result"), }; } private string[] List() { return Reports.Ordered(tracker.Tasks) .Select(task => $"[{(task.Done ? "x" : " ")}] {task.Id} {task.Priority} {task.Due:yyyy-MM-dd} {task.Title}") .ToArray(); } private string[] BuildReport() { Report report = Reports.Build(tracker.Tasks.ToList(), clock.Today); var lines = new List<string> { $"Open: {report.Open}", $"Done: {report.Done}", $"Overdue: {report.Overdue}", }; foreach (Priority priority in Enum.GetValues<Priority>().Reverse()) { report.OpenByPriority.TryGetValue(priority, out int count); lines.Add($"{priority}: {count}"); } return lines.ToArray(); } private static string[] Store(string path, Func<ITaskStore, Result<int>> action, string verb) { if (path.Length == 0) { return Error("a file name is required"); } return action(new JsonFileStore(path)) switch { Ok<int> ok => new[] { $"{verb} {ok.Value} tasks" }, Fail<int> fail => Error(fail.Error), _ => throw new InvalidOperationException("unknown result"), }; } private string[] SetToday(string argument) { if (!TryParseDate(argument, out DateOnly today)) { return Error($"bad date {argument}"); } clock = new FixedClock(today); return new[] { $"Today is {today:yyyy-MM-dd}" }; } } #nullable enable namespace TaskTracker; public class Tracker { public const int MaxTitleLength = 60; private readonly List<TaskItem> tasks = new(); private int nextId = 1; public IReadOnlyList<TaskItem> Tasks => tasks; public Result<TaskItem> Add(string title, Priority priority, DateOnly due) { string trimmed = title.Trim(); if (trimmed.Length == 0 || trimmed.Length > MaxTitleLength) { return new Fail<TaskItem>($"title must be 1 to {MaxTitleLength} characters"); } var task = new TaskItem(nextId, trimmed, priority, due); nextId++; tasks.Add(task); return new Ok<TaskItem>(task); } public Result<TaskItem> Complete(int id) { int index = tasks.FindIndex(task => task.Id == id); if (index < 0) { return new Fail<TaskItem>($"no task {id}"); } tasks[index] = tasks[index] with { Done = true }; return new Ok<TaskItem>(tasks[index]); } public Result<TaskItem> Remove(int id) { int index = tasks.FindIndex(task => task.Id == id); if (index < 0) { return new Fail<TaskItem>($"no task {id}"); } TaskItem removed = tasks[index]; tasks.RemoveAt(index); return new Ok<TaskItem>(removed); } public Result<int> Save(ITaskStore store) { try { store.Save(tasks); return new Ok<int>(tasks.Count); } catch (IOException e) { return new Fail<int>(e.Message); } } // Replaces the tasks only after everything loaded and validated. public Result<int> Load(ITaskStore store) { IReadOnlyList<TaskItem> loaded; try { loaded = store.Load(); } catch (IOException e) { return new Fail<int>(e.Message); } catch (StoreFormatException e) { return new Fail<int>(e.Message); } // Nullable annotations are not enforced when JSON is read, so a list can hold null. if (loaded.Any(task => task is null)) { return new Fail<int>("saved data has an empty entry"); } if (loaded.Any(task => task.Title is null || task.Title.Trim().Length == 0 || task.Title.Length > MaxTitleLength)) { return new Fail<int>("saved data has an invalid title"); } // An enum accepts any number of its underlying type, such as 99 in a saved file. if (loaded.Any(task => !Enum.IsDefined(task.Priority))) { return new Fail<int>("saved data has an invalid priority"); } if (loaded.Select(task => task.Id).Distinct().Count() != loaded.Count || loaded.Any(task => task.Id < 1)) { return new Fail<int>("saved data has invalid ids"); } tasks.Clear(); tasks.AddRange(loaded); nextId = tasks.Count == 0 ? 1 : tasks.Max(task => task.Id) + 1; return new Ok<int>(tasks.Count); } } #nullable enable namespace TaskTracker; public enum Priority { Low, Normal, High } public record TaskItem(int Id, string Title, Priority Priority, DateOnly Due, bool Done = false); // A result is exactly one of two cases, so a caller has to look before using a value. public abstract record Result<T>; public sealed record Ok<T>(T Value) : Result<T>; public sealed record Fail<T>(string Error) : Result<T>; #nullable enable using System.Text.Json; using System.Text.Json.Serialization; namespace TaskTracker; public interface ITaskStore { IReadOnlyList<TaskItem> Load(); void Save(IEnumerable<TaskItem> tasks); } public class StoreFormatException : Exception { public StoreFormatException(string message, Exception? inner = null) : base(message, inner) { } } public class JsonFileStore : ITaskStore { private static readonly JsonSerializerOptions Options = new() { WriteIndented = true, Converters = { new JsonStringEnumConverter() }, }; private readonly string path; public JsonFileStore(string path) { this.path = path; } public IReadOnlyList<TaskItem> Load() { string json = File.ReadAllText(path); List<TaskItem>? loaded; try { loaded = JsonSerializer.Deserialize<List<TaskItem>>(json, Options); } catch (JsonException e) { throw new StoreFormatException($"{path} is not valid task data", e); } // The text "null" is valid JSON but not a task list; an empty list is written []. return loaded ?? throw new StoreFormatException($"{path} is not valid task data"); } // Write to a temporary file first, so a failed write can't damage the last good save. public void Save(IEnumerable<TaskItem> tasks) { string temporary = path + ".tmp"; File.WriteAllText(temporary, JsonSerializer.Serialize(tasks, Options)); File.Move(temporary, path, overwrite: true); } } #nullable enable namespace TaskTracker; public record Report(int Open, int Done, int Overdue, IReadOnlyDictionary<Priority, int> OpenByPriority); public static class Reports { // Open tasks first, then soonest due, then highest priority; the id keeps ties stable. public static IEnumerable<TaskItem> Ordered(IEnumerable<TaskItem> tasks) { return tasks .OrderBy(task => task.Done) .ThenBy(task => task.Due) .ThenByDescending(task => task.Priority) .ThenBy(task => task.Id); } public static IEnumerable<TaskItem> Overdue(IEnumerable<TaskItem> tasks, DateOnly today) { return tasks.Where(task => !task.Done && task.Due < today); } public static Report Build(IReadOnlyCollection<TaskItem> tasks, DateOnly today) { var open = tasks.Where(task => !task.Done).ToList(); var byPriority = open.GroupBy(task => task.Priority).ToDictionary(group => group.Key, group => group.Count()); return new Report(open.Count, tasks.Count - open.Count, Overdue(tasks, today).Count(), byPriority); } } #nullable enable namespace TaskTracker; public interface IClock { DateOnly Today { get; } } public class SystemClock : IClock { public DateOnly Today => DateOnly.FromDateTime(DateTime.Now); } public class FixedClock : IClock { public DateOnly Today { get; } public FixedClock(DateOnly today) { Today = today; } } today 2026-11-02 add High 2026-11-01 Write report add Low 2026-11-20 Read chapter add Normal 2026-11-05 Review notes add Urgent 2026-11-05 Bad priority done 2 done 9 list report save tasks.json remove 3 list load tasks.json list

Change the input and run it again. Try a date that doesn't exist, a 61-character title, a done on a removed task, and a load of a file that was never saved.

In this browser, a saved file lasts only for one Run, which is why the sample saves and loads in one go. When you run the project on your computer, tasks.json stays in the folder.

Follow one command

Here's what happens for done 2.

  1. Program.cs reads the line and passes it to Commands.Execute. It prints whatever lines come back.
  2. Execute splits off the first word, and its switch chooses WithId, passing the method tracker.Complete as a Func.
  3. WithId parses the id, calls the function, then uses a switch on the Result to build the output line. remove shares this code.
  4. Tracker.Complete looks up the task and replaces it, using with { Done = true }. It never touches text formatting.

Commands return text, rather than printing, so a check can compare it directly.

Three decisions to notice

Errors are values until the edge. Tracker.Add returns Result<TaskItem>, and a bad title can't crash the program. A disk failure does throw from JsonFileStore, and Tracker.Load converts it into a Fail at the boundary.

Load is all or nothing. It parses and validates into a separate variable. Only then does it call tasks.Clear(). nextId comes from the highest loaded id, not from the count, so a load never hands out an id that a saved task still holds. It is not a promise that ids are never reused: the file stores only tasks, so if you remove the task with the highest id and then save and load, the next add gets that id again (Checks.cs shows id 2 coming back). Within one session, a removed id isn't used again.

Today is an input. Reports.Build takes today as a parameter, and Commands asks an IClock. The today command swaps in a FixedClock, which is why this program's output is repeatable.

Practice the core idea

WithId works because a method can be passed as a value. Predict this reduced version.

One helper, two commands C#
#nullable enable

var names = new Dictionary<int, string> { [1] = "Read" };

Console.WriteLine(WithId("1", "Found", Find));
Console.WriteLine(WithId("2", "Found", Find));
Console.WriteLine(WithId("x", "Found", Find));
Console.WriteLine(WithId("1", "Removed", Remove));
Console.WriteLine(WithId("1", "Removed", Remove));

static string WithId(string text, string verb, Func<int, string> action)
{
    if (!int.TryParse(text, out int id))
    {
        return $"Error: bad id {text}";
    }
    return $"{verb}: {action(id)}";
}

string Find(int id) => names.GetValueOrDefault(id, "nothing");

string Remove(int id) => names.Remove(id, out string? name) ? name : "nothing";
Check your prediction
Text
Found: Read
Found: nothing
Error: bad id x
Removed: Read
Removed: nothing

Your turn

Exercise

A dispatcher of your own

Write a small class Calculator with an int Total, and a method Execute(string line) that returns one string. It supports add <n>, sub <n> and show. Use a list pattern and a helper that takes a Func<int, int> for the two arithmetic commands. A bad number or unknown command returns text starting with Error:.

Run the lines add 5, sub 2, show, add x and jump, printing each result.

When it works, it prints:

Text
Total: 5
Total: 3
Total: 3
Error: bad number x
Error: unknown command jump
Your workspace C#
foreach (string line in new[] { "add 5", "sub 2", "show", "add x", "jump" })
{
    Console.WriteLine(line);
}
Hint 1: the idea

add and sub differ only in the arithmetic, so the helper does the parsing and storing, and each command passes a lambda for its one difference.

Hint 2: a first step

Split on spaces and switch on the array, starting with ["show"]. Then add ["add", var text].

Show one solution
C#
var calculator = new Calculator();

foreach (string line in new[] { "add 5", "sub 2", "show", "add x", "jump" })
{
    Console.WriteLine(calculator.Execute(line));
}

class Calculator
{
    public int Total { get; private set; }

    public string Execute(string line) => line.Split(' ') switch
    {
        ["show"] => $"Total: {Total}",
        ["add", var text] => Apply(text, amount => Total + amount),
        ["sub", var text] => Apply(text, amount => Total - amount),
        _ => $"Error: unknown command {line}",
    };

    private string Apply(string text, Func<int, int> change)
    {
        if (!int.TryParse(text, out int amount))
        {
            return $"Error: bad number {text}";
        }
        Total = change(amount);
        return $"Total: {Total}";
    }
}
Text
Total: 5
Total: 3
Total: 3
Error: bad number x
Error: unknown command jump

A list pattern on line.Split(' ') matches both the command and how many words it has, so add with no number falls through to the unknown-command arm instead of throwing. add and sub share Apply, which parses once and takes the actual change as a lambda, so the error handling exists in one place. Total changes only after the number has parsed, which is why add x leaves it at 3.

Was this article helpful?

Your response is saved on this device.