Skip to content
KALANBLON
Show contents

Chapter 6 of 7 · 25 min

Project: a task manager

By the end of this chapter, you'll be able to

  • Design classes from the rules of a problem
  • Use exceptions to refuse invalid operations
  • Sort objects by several criteria with Comparator
  • Read and interpret commands until the end of input
  • Test a program with a scenario whose result you know

Step 1: rules and design

The rules:

  1. a task has a unique number assigned automatically, a title, a priority from 1 (urgent) to 3 (whenever), and a done / to-do state;
  2. an empty title or a priority outside 1 to 3 is refused;
  3. you can't complete an unknown task, nor a task that's already done;
  4. the list is displayed sorted by priority, then by number.

Two classes:

  • Task: one task and its state rule (it can only be completed once);
  • TaskList: the collection, the numbering and the searches.

main reads commands (add 2 Title of the task, done 1, list) and displays the results or the errors.

main catches the exception and displays its message. The program carries on.

Step 7 of 7
Text description of the animation
  1. We read a command line.
  2. split cuts the line into pieces: the command, then its arguments.
  3. The list looks for the task by its number.
  4. The task changes state. It's the task itself that applies its own rule.
  5. main displays the result.
  6. With the same command a second time, the task refuses and throws an exception.
  7. main catches the exception and displays its message. The program carries on.

Step 2: the program

class Task {
    private final int id;
    private final String title;
    private final int priority;
    private boolean done;

    Task(int id, String title, int priority) {
        this.id = id;
        this.title = title;
        this.priority = priority;
    }

    int getId() { return id; }
    int getPriority() { return priority; }

    void complete() {
        if (done) {
            throw new IllegalStateException("task " + id + " is already done");
        }
        done = true;
    }

    @Override
    public String toString() {
        return (done ? "[x] " : "[ ] ") + id + " (P" + priority + ") " + title;
    }
}

class TaskList {
    private final List<Task> tasks = new ArrayList<>();
    private int nextId = 1;

    int add(String title, int priority) {
        if (title == null || title.isBlank()) {
            throw new IllegalArgumentException("the title is empty");
        }
        if (priority < 1 || priority > 3) {
            throw new IllegalArgumentException("invalid priority (1 to 3): " + priority);
        }
        tasks.add(new Task(nextId, title.strip(), priority));
        return nextId++;
    }

    void complete(int id) {
        for (Task t : tasks) {
            if (t.getId() == id) {
                t.complete();
                return;
            }
        }
        throw new IllegalArgumentException("no task number " + id);
    }

    List<Task> sorted() {
        var copy = new ArrayList<>(tasks);
        copy.sort(Comparator.comparing(Task::getPriority).thenComparing(Task::getId));
        return copy;
    }
}

void main() {
    var list = new TaskList();
    String line;
    while ((line = IO.readln()) != null) {
        String[] parts = line.strip().split(" ", 3);
        try {
            switch (parts[0]) {
                case "add" -> {
                    int id = list.add(parts[2], Integer.parseInt(parts[1]));
                    IO.println("Task " + id + " added");
                }
                case "done" -> {
                    list.complete(Integer.parseInt(parts[1]));
                    IO.println("Task " + parts[1] + " done");
                }
                case "list" -> {
                    for (Task t : list.sorted()) {
                        IO.println(t);
                    }
                }
                default -> IO.println("Unknown command: " + parts[0]);
            }
        } catch (IllegalArgumentException | IllegalStateException e) {
            IO.println("Error: " + e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            IO.println("Error: an argument is missing");
        }
    }
}

A few choices worth noticing:

  • IO.readln() returns null when there's nothing left to read: the loop stops cleanly at the end of input.
  • split(" ", 3) cuts into at most 3 pieces: so the title, which comes last, can contain spaces.
  • Each class applies its rules: Task refuses to be completed twice, TaskList validates titles and priorities. main only orchestrates.
  • sorted() returns a sorted copy: the list's internal order isn't changed, and nobody else can touch the private list.
  • catch (IllegalArgumentException | IllegalStateException e) handles two types of exceptions the same way. Since NumberFormatException is a kind of IllegalArgumentException, done abc is covered too.

Step 3: test a complete scenario

We write a scenario that goes through every rule, and predict the output before running the program:

add 2 Revise the Java course
add 1 Pay the electricity bill
add 3 Water the plants
done 2
done 2
done 9
add 5 Impossible task
add 2
list
Task 1 added
Task 2 added
Task 3 added
Task 2 done
Error: task 2 is already done
Error: no task number 9
Error: invalid priority (1 to 3): 5
Error: an argument is missing
[x] 2 (P1) Pay the electricity bill
[ ] 1 (P2) Revise the Java course
[ ] 3 (P3) Water the plants

Notice that the refused task (priority 5) didn't use up a number: nextId is only incremented after the checks.

Your turn

Worked exercise

Worked exercise: the summary

Add to TaskList a method int remainingCount() and a method List<Task> urgent(), which returns the priority 1 tasks that aren't done yet. For that, add to Task a getter boolean isDone(). The solution tests the methods without the keyboard and must display 2 task(s) left out of 3 and Urgent: [[ ] 3 (P1) Call the plumber].

Hint 1
remainingCount goes through the list and counts the tasks for which isDone() is false.
Hint 2
urgent builds a new ArrayList with the tasks that meet both conditions. Displaying a list calls each task's toString.
Show the solution and common mistakes
class Task {
    private final int id;
    private final String title;
    private final int priority;
    private boolean done;

    Task(int id, String title, int priority) {
        this.id = id;
        this.title = title;
        this.priority = priority;
    }

    int getPriority() { return priority; }
    boolean isDone() { return done; }
    void complete() { done = true; }

    @Override
    public String toString() {
        return (done ? "[x] " : "[ ] ") + id + " (P" + priority + ") " + title;
    }
}

class TaskList {
    private final List<Task> tasks = new ArrayList<>();
    private int nextId = 1;

    Task add(String title, int priority) {
        var t = new Task(nextId++, title, priority);
        tasks.add(t);
        return t;
    }

    int remainingCount() {
        int n = 0;
        for (Task t : tasks) {
            if (!t.isDone()) {
                n++;
            }
        }
        return n;
    }

    List<Task> urgent() {
        var result = new ArrayList<Task>();
        for (Task t : tasks) {
            if (t.getPriority() == 1 && !t.isDone()) {
                result.add(t);
            }
        }
        return result;
    }

    int total() { return tasks.size(); }
}

void main() {
    var list = new TaskList();
    list.add("Pay the rent", 1).complete();
    list.add("Read a chapter", 3);
    list.add("Call the plumber", 1);
    IO.println(list.remainingCount() + " task(s) left out of " + list.total());
    IO.println("Urgent: " + list.urgent());
}
2 task(s) left out of 3
Urgent: [[ ] 3 (P1) Call the plumber]

To keep to the essentials, this solution lightens the checks from step 2. In your program, keep them all.

Common mistakes:

  • Adding a remainingCount attribute updated by hand: it always ends up out of sync. Computing from the list is safer.
  • Returning tasks filtered by changing it (with removeIf): you'd delete tasks from the real list.

Summary

  1. 1Start from the rules of the problem: each class applies the ones that concern it.
  2. 2Exceptions refuse invalid operations; main catches them and displays a clear message.
  3. 3Comparator.comparing(…).thenComparing(…) sorts by several criteria.
  4. 4Never let a modifiable internal list out: return a copy.
  5. 5Test with a scenario that goes through every rule, predicting the output in advance.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.