Skip to content

Extend the Planner

The Course
•
15 min study

An extension should start with a user-visible rule, not with a new library. Our planner can report all accepted and completed minutes, so an unfinished-time report is a natural next operation. Add remainingMinutes() to Planner, returning plannedMinutes() minus completedMinutes(). The existing completion invariants ensure the result is nonnegative without storing another changing counter.

Write the evidence first

Decide what remainingMinutes() should return at each stage of one planner's life before writing the method:

StageremainingMinutes()
empty planner0
after adding Java 25 and Reading 1035
after complete(0)10
after complete(0) again10
after complete(1)0

The fourth row is the interesting one: completing a session twice must not subtract its minutes twice.

A compiler failure proves only that the API is missing. Once the method exists, the meaningful evidence is that its returned values match the contract. Keep that distinction clear when you introduce intentional defects.

Keep one source of truth

It is tempting to add a stored remaining field and update it in add and complete. That creates a new obligation: every mutation must keep three totals synchronized, including repeated completion and failed additions. A derived result avoids that extra mutable state. Reuse already-tested methods instead of copying their loops and hoping future changes keep every version aligned.

Do not add persistence, a GUI or a framework for this task. Finish one precise change, rerun the existing tests, then decide what the next useful capability is. Small steps make regressions easier to locate.

A derived result need not have its own field Java
public class Main {
    public static void main(String[] args) {
        System.out.println(remaining(35, 0));
        System.out.println(remaining(35, 25));
        System.out.println(remaining(35, 35));
    }

    static int remaining(int planned, int completed) {
        return planned - completed;
    }
}
Check your prediction
Text
35
10
0

This works because completed can never exceed planned: in the project, both totals come from the same list of sessions, and a session's minutes count as completed at most once. Don't reuse this bare subtraction for unrelated inputs without stating that precondition.

Your turn

Exercise

Add remainingMinutes to the planner

This workspace is the real project, with PlannerTest.java as the entry. Run it once first: it prints All planner checks passed. Then:

  1. In PlannerTest.java, add the five checks from "Write the evidence first" above, just before the final println, and run. It fails to compile, because remainingMinutes does not exist yet.
  2. In Planner.java, add public int remainingMinutes() and run again until all checks pass, old and new.
Your workspace: the planner and its tests Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); Planner planner = new Planner(); // Two lines per session: a topic, then whole-number minutes. while (input.hasNextLine()) { String topic = input.nextLine(); if (!input.hasNextLine()) { System.out.println("Missing minutes for: " + topic); break; } String minutesText = input.nextLine(); try { int minutes = Integer.parseInt(minutesText.trim()); planner.add(topic, minutes); } catch (NumberFormatException error) { System.out.println("Skipped: minutes must be a whole number"); } catch (IllegalArgumentException error) { System.out.println("Skipped: " + error.getMessage()); } catch (IllegalStateException error) { System.out.println(error.getMessage()); break; } } // This demo completes the first accepted session, if there is one. planner.complete(0); System.out.println(planner.report()); } } import java.util.ArrayList; public class Planner { private final ArrayList<Session> sessions = new ArrayList<>(); public void add(String topic, int minutes) { if (sessions.size() >= 100) { throw new IllegalStateException("Plan is full"); } // Construct and validate before changing the list. Session session = new Session(topic, minutes); sessions.add(session); } public int size() { return sessions.size(); } public boolean complete(int index) { if (index < 0 || index >= sessions.size()) { return false; } sessions.get(index).complete(); return true; } public int plannedMinutes() { int total = 0; for (Session session : sessions) { total += session.minutes(); } return total; } public int completedMinutes() { int total = 0; for (Session session : sessions) { if (session.isDone()) { total += session.minutes(); } } return total; } public String report() { int planned = plannedMinutes(); int completed = completedMinutes(); return size() + " sessions, " + completed + "/" + planned + " min complete"; } } public class Session { private final String topic; private final int minutes; private boolean done; public Session(String topic, int minutes) { if (topic == null || topic.trim().isEmpty()) { throw new IllegalArgumentException("Topic is required"); } if (minutes < 1 || minutes > 240) { throw new IllegalArgumentException("Minutes must be 1 to 240"); } this.topic = topic.trim(); this.minutes = minutes; } public String topic() { return topic; } public int minutes() { return minutes; } public boolean isDone() { return done; } public void complete() { // Completing a session twice still counts it only once. done = true; } } public class PlannerTest { public static void main(String[] args) { Planner empty = new Planner(); check("empty report", empty.report().equals("0 sessions, 0/0 min complete")); check("empty completion", !empty.complete(0)); Planner planner = new Planner(); planner.add(" Java ", 25); planner.add("Reading", 10); check("planned total", planner.plannedMinutes() == 35); check("initial completion", planner.completedMinutes() == 0); check("complete first", planner.complete(0)); check("complete again", planner.complete(0)); check("count once", planner.completedMinutes() == 25); check("negative index", !planner.complete(-1)); check("index at size", !planner.complete(2)); check("report", planner.report().equals("2 sessions, 25/35 min complete")); Session normalized = new Session(" Java ", 25); check("trim topic", normalized.topic().equals("Java")); check("new session", !normalized.isDone()); check("separate planner", empty.plannedMinutes() == 0); expectInvalid(planner, null, 25); expectInvalid(planner, " ", 25); expectInvalid(planner, "Bad", 0); expectInvalid(planner, "Bad", 241); check("failed additions do not change size", planner.size() == 2); check("failed additions do not change total", planner.plannedMinutes() == 35); Planner full = new Planner(); for (int index = 0; index < 100; index++) { full.add("Topic", 240); } check("bounded total", full.plannedMinutes() == 24000); boolean rejected = false; try { full.add("Extra", 1); } catch (IllegalStateException error) { rejected = true; } check("full plan rejects addition", rejected); check("full plan unchanged", full.size() == 100); System.out.println("All planner checks passed"); } private static void expectInvalid(Planner planner, String topic, int minutes) { boolean rejected = false; try { planner.add(topic, minutes); } catch (IllegalArgumentException error) { rejected = true; } check("invalid addition rejected", rejected); } private static void check(String label, boolean condition) { if (!condition) { throw new AssertionError(label); } } }
Hint 1: the idea

The planner can already answer "how much is planned" and "how much is done". The new method needs no new field and no loop: it combines those two answers. The tests need a planner whose state you change between checks, so the same call gives a different answer after each complete().

Hint 2: a first step

In Planner.java, put the new method inside the class, next to completedMinutes(). In PlannerTest.java, make a fresh Planner extended = new Planner(); and check it returns 0 before you add anything. Then add the 25 and 10 sessions and check 35.

Show one solution

Planner.java, with the new method above report():

Java
import java.util.ArrayList;

public class Planner {
    private final ArrayList<Session> sessions = new ArrayList<>();

    public void add(String topic, int minutes) {
        if (sessions.size() >= 100) {
            throw new IllegalStateException("Plan is full");
        }

        // Construct and validate before changing the list.
        Session session = new Session(topic, minutes);
        sessions.add(session);
    }

    public int size() {
        return sessions.size();
    }

    public boolean complete(int index) {
        if (index < 0 || index >= sessions.size()) {
            return false;
        }

        sessions.get(index).complete();
        return true;
    }

    public int plannedMinutes() {
        int total = 0;

        for (Session session : sessions) {
            total += session.minutes();
        }

        return total;
    }

    public int completedMinutes() {
        int total = 0;

        for (Session session : sessions) {
            if (session.isDone()) {
                total += session.minutes();
            }
        }

        return total;
    }

    public int remainingMinutes() {
        return plannedMinutes() - completedMinutes();
    }

    public String report() {
        int planned = plannedMinutes();
        int completed = completedMinutes();

        return size() + " sessions, " + completed + "/" + planned + " min complete";
    }
}

Lines added to PlannerTest.java, before the final println:

Java
        Planner extended = new Planner();
        check("remaining empty", extended.remainingMinutes() == 0);
        extended.add("Java", 25);
        extended.add("Reading", 10);
        check("remaining new", extended.remainingMinutes() == 35);
        extended.complete(0);
        check("remaining after first", extended.remainingMinutes() == 10);
        extended.complete(0);
        check("remaining after repeat", extended.remainingMinutes() == 10);
        extended.complete(1);
        check("remaining all done", extended.remainingMinutes() == 0);
Text
All planner checks passed

remainingMinutes() calls the two methods the old tests already check, so it inherits their rules: a repeated complete(0) is counted once, which is why the "after repeat" check still expects 10. Each check follows a real complete() call on the same object, so the tests prove the value tracks the planner's state, not just that a subtraction works.

Change it and explain

After implementing the instance method in the project, deliberately return plannedMinutes() without subtracting completion and show which new check fails. Restore it and rerun the old tests too. A new feature should preserve the old contract unless you explicitly decide to change that contract.

For a second extension, consider a method returning the count of unfinished sessions. Define its empty and repeated-completion behavior before coding. Do not expose the internal ArrayList just to make a caller count it; keep the model responsible for its own collection.

Was this article helpful?

Your response is saved on this device.