Skip to content

Checkpoint: A Small Planner

The Course
•
30 min study

This checkpoint brings together the whole day: a record for the data, a class for the rules, and a method returning a summary that callers can't accidentally break. It's also a first draft of the planner you'll finish on Day 7.

Warm up: a list the outside can't change

If a class hands out its private list, callers can change it and skip every rule. IReadOnlyList<T> is a view of the same list without Add or Remove, and it's how you share data without giving up control. It's an interface: a type that only lists what something can do (here: count, and read by index) without saying how. A List<T> can do all of that, so a List<T> can be returned wherever an IReadOnlyList<T> is asked for. Writing your own interfaces comes in the intermediate course; for now you only need to use this one.

A read-only view C#
var shelf = new Shelf();
shelf.Add("Maths");
shelf.Add("");
Console.WriteLine(shelf.Titles.Count);
Console.WriteLine(shelf.Titles[0]);

class Shelf
{
    private readonly List<string> titles = new();

    public IReadOnlyList<string> Titles => titles;

    public void Add(string title)
    {
        if (title != "")
        {
            titles.Add(title);
        }
    }
}
Check your prediction
Text
1
Maths

Try shelf.Titles.Add("Oops"); and read the error. new() with no type repeats the one from the declaration, a common shorthand for fields.

Build it yourself

Exercise

The first planner

The workspace declares a record StudyTask(string Title, int Minutes, bool Done), a record Summary(int Tasks, int Planned, int Completed, int Remaining), and the outline of a class Planner. In Summary, Tasks is how many tasks are stored, and the other three are minutes: Planned adds up every task's minutes, Completed only the done tasks' minutes, and Remaining is the difference. Fill in the three methods marked TODO:

  • Add(StudyTask task) returns false and stores nothing unless the minutes are from 1 to 180 and the title isn't blank;
  • Complete(int index) returns false for an index that doesn't exist, and otherwise marks that task done;
  • Summarize() returns a Summary built from the stored tasks.

Add Read (25, not done), Review (10, done) and an invalid task with 0 minutes, then complete the first task and print the summary. Because Summary is a record, you can print it directly. Also write checks that compare results with ==, and have them print only when something fails. When every check passes, the only line printed is the summary:

Text
Summary { Tasks = 2, Planned = 35, Completed = 35, Remaining = 0 }

If time is short, do Add and Summarize first, and come back for Complete.

Your workspace C#
var planner = new Planner();
Console.WriteLine(planner.Add(new StudyTask("Read", 25, false)));
Console.WriteLine(planner.Summarize());

record StudyTask(string Title, int Minutes, bool Done);

record Summary(int Tasks, int Planned, int Completed, int Remaining);

class Planner
{
    private readonly List<StudyTask> tasks = new();

    public IReadOnlyList<StudyTask> Tasks => tasks;

    public bool Add(StudyTask task)
    {
        // TODO: refuse minutes outside 1 to 180, and a blank title.
        tasks.Add(task);
        return true;
    }

    public bool Complete(int index)
    {
        // TODO: refuse an index that doesn't exist, then mark that task done.
        return false;
    }

    public Summary Summarize()
    {
        // TODO: add up the planned and completed minutes.
        return new Summary(tasks.Count, 0, 0, 0);
    }
}
Hint 1: the idea

The planner owns the rules, so every change goes through its methods. A task is a record, which means completing it replaces the list entry.

Hint 2: a first step

Write Add and Summarize first, and check that an empty planner's summary equals a Summary of four zeros.

Show one solution
C#
int failures = 0;

var planner = new Planner();
Check(planner.Summarize() == new Summary(0, 0, 0, 0), "an empty plan totals zero");
Check(planner.Add(new StudyTask("Read", 25, false)), "accepts a valid task");
Check(planner.Add(new StudyTask("Review", 10, true)), "accepts a done task");
Check(!planner.Add(new StudyTask("Bad", 0, false)), "refuses 0 minutes");
Check(!planner.Add(new StudyTask(" ", 10, false)), "refuses a blank title");
Check(planner.Complete(0), "completes the first task");
Check(!planner.Complete(2), "refuses an index past the end");
Check(planner.Tasks.Count == 2, "stores only valid tasks");

Console.WriteLine(planner.Summarize());

void Check(bool passed, string name)
{
    if (!passed)
    {
        Console.WriteLine($"FAILED: {name}");
        failures++;
    }
}

record StudyTask(string Title, int Minutes, bool Done);

record Summary(int Tasks, int Planned, int Completed, int Remaining);

class Planner
{
    private readonly List<StudyTask> tasks = new();

    public IReadOnlyList<StudyTask> Tasks => tasks;

    public bool Add(StudyTask task)
    {
        if (task.Minutes < 1 || task.Minutes > 180 || string.IsNullOrWhiteSpace(task.Title))
        {
            return false;
        }
        tasks.Add(task);
        return true;
    }

    public bool Complete(int index)
    {
        if (index < 0 || index >= tasks.Count)
        {
            return false;
        }
        tasks[index] = tasks[index] with { Done = true };
        return true;
    }

    public Summary Summarize()
    {
        int planned = 0;
        int completed = 0;
        foreach (StudyTask task in tasks)
        {
            planned += task.Minutes;
            if (task.Done)
            {
                completed += task.Minutes;
            }
        }
        return new Summary(tasks.Count, planned, completed, planned - completed);
    }
}
Text
Summary { Tasks = 2, Planned = 35, Completed = 35, Remaining = 0 }

Every rule is in Planner, and the list is private, so Add and Complete are the only ways in. Completing replaces the list entry with with { Done = true }, because a record can't be changed. Summarize works out the totals from the tasks each time instead of keeping running counts, so completing a task twice can't count its minutes twice. That's also why Remaining is planned - completed rather than a third total that could disagree with the other two.

What happens if you call Complete(0) twice? Decide what should happen and add a check for it. Then try to change a task from outside the planner, and notice which attempts the compiler rejects.

Was this article helpful?

Your response is saved on this device.