Skip to content

Task Tracker

The Course
•
20 min study

The capstone turns the week's ideas into one application. A Task is immutable; a repository owns unique IDs; a parser validates records; a service chooses recovery and reporting behavior; Main prints results. No new framework or language feature is needed.

Trace one record through these boundaries before editing. Input is id;title;minutes;status, not general CSV. Blank lines are skipped, rejected records are reported, duplicates never overwrite earlier tasks, and valid records after a bad one still import. Each browser run starts a new in-memory store.

Work through the example

An immutable update creates a new value rather than changing a shared object. Any earlier snapshot still sees the old state. In the full project withStatus validates the replacement through Task's constructor. Identity and state are separate: a task keeps its ID when its status changes.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        Task before = new Task("A1", false);
        Task after = before.complete();
        System.out.println(before.done());
        System.out.println(after.done());
        System.out.println(after.id());
    }
}

final class Task {
    private final String id;
    private final boolean done;

    Task(String id, boolean done) {
        this.id = id;
        this.done = done;
    }

    String id() {
        return id;
    }

    boolean done() {
        return done;
    }

    Task complete() {
        return new Task(id, true);
    }
}
Check your prediction
Text
false
true
A1

Compare the behavior

The repository must replace an existing value under the same key. This miniature trace shows the operation, not the full contract checks. The complete MemoryTaskRepository rejects missing replacements first. Application code should call that repository rather than reach into its map.

Trace the changed case Java
import java.util.Map;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        Map<String, String> titles = new LinkedHashMap<>();
        titles.put("A1", "Old");
        if (titles.containsKey("A1")) {
            titles.put("A1", "Updated");
        }
        System.out.println(titles.size());
        System.out.println(titles.get("A1"));
    }
}
Check your prediction
Text
1
Updated

Follow one record through the files

FileResponsibilityRule it protects
Status / TaskRepresent one immutable taskValid title, ID, minutes and status
TaskRepositoryState the storage contractUnique add, explicit replacement, absent lookup
MemoryTaskRepositoryOwn the mapRejection before mutation; copied result lists
TaskParserConvert four text fieldsCorrect field count, numeric text and enum name
TaskServiceCoordinate operationsPer-record recovery, completion and report ordering
ImportResultReturn accepted count and error messagesError-list copies protect the result
Timed / ReportsGeneric reports over anything with minutes? extends Timed input; <T extends Timed> keeps the caller's type
Main / TrackerTestPresent a demo / check behaviorExpected outputs and failure cases

Trace A1;Read chapter;25;TODO. The parser splits four fields and converts minutes and status. Task's constructor trims and validates ID/title and checks the 1–240 range. Only a fully constructed Task reaches repository.add. If A1 already exists, add rejects before put, so the original object remains. importFrom catches this expected input rejection, records the physical line number and moves to the next record.

The sample accepts B2, A1 and C3, and rejects a malformed line plus the second A1. complete("B2") looks up the existing task and replaces it with a new DONE value. openOrdered excludes B2, orders the remaining tasks by minutes then ID, and returns an unmodifiable result list. That leaves C3 before A1 and a total of 45 minutes; Reports.longest picks A1. Try predicting the report before running Main.

The repository's all() returns a separate mutable list, while the service's openOrdered() returns an unmodifiable list. Neither permits changing the repository's membership. Task objects are immutable, so sharing their references across those snapshots is safe. ID is the explicit map key: the project does not override Task.equals or use task titles as identity.

No operation here reads files or contacts a service. Day 6's reader skills are used in TaskService: importFrom reads a BufferedReader it does not own and declares IOException, and importLines wraps an array in a StringReader with try-with-resources, turning an unexpected IOException into IllegalStateException. Blank lines are skipped but still counted for line numbers. The importer retains previous successful records: it is deliberately not an all-or-nothing transaction. Complete returns false for a missing ID, and repeated completion returns true without adding another contribution. These policies are checked in TrackerTest.

Run the complete project

Two library calls connect the earlier lessons to this project. tasks.values() reads the map's stored Task values; new ArrayList<>(tasks.values()) copies them into the independent list returned by all(). thenComparing(Task::id) extracts an ID as the secondary sort key, equivalent to thenComparing(task -> task.id()); Java compares those String keys in natural order. This overload takes one Task to extract a key, unlike Day 5's two-string comparison function.

In importFrom, lineNumber++ runs before the blank check, so a skipped blank line still counts as a physical line. repository.add(parser.parse(line)) first parses the line, then passes the resulting Task to add. If either step rejects it, accepted is not incremented. Trace those two steps separately before trying to shorten your own code.

Read the source tabs in this order: Status, Timed, Task, TaskRepository, MemoryTaskRepository, TaskParser, ImportResult, Reports, TaskService, then Main or TrackerTest. Reports is where Day 4 reappears: totalMinutes accepts a List<? extends Timed>, so it can read a List<Task>, and longest is declared <T extends Timed> T, so Main gets a Task back and can call id() on it without a cast. The marked entry is Main.java. Other files are compiled with it, not executed independently. Keep the filenames and public class names aligned.

Run the application Java
import java.util.ArrayList; import java.util.List; public final class ImportResult { private final int accepted; private final List<String> errors; public ImportResult(int accepted, List<String> errors) { this.accepted = accepted; this.errors = new ArrayList<>(errors); } public int accepted() { return accepted; } public List<String> errors() { return new ArrayList<>(errors); } } public class Main { public static void main(String[] args) { TaskRepository repository = new MemoryTaskRepository(); TaskService service = new TaskService(repository, new TaskParser()); String[] lines = { "B2;Practice loops;20;TODO", "bad record", "A1;Read chapter;25;TODO", "A1;Duplicate;10;TODO", "C3;Write tests;20;TODO" }; ImportResult result = service.importLines(lines); System.out.println("Accepted: " + result.accepted()); System.out.println("Rejected: " + result.errors().size()); service.complete("B2"); for (Task task : service.openOrdered()) { System.out.println(task.id() + ": " + task.title() + " (" + task.minutes() + ")"); } System.out.println("Open minutes: " + service.openMinutes()); Task longest = Reports.longest(service.openOrdered()); System.out.println("Longest open: " + longest.id()); } } import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class MemoryTaskRepository implements TaskRepository { private final Map<String, Task> tasks = new LinkedHashMap<>(); @Override public void add(Task task) { if (task == null || tasks.containsKey(task.id())) { throw new IllegalArgumentException("duplicate or missing task"); } tasks.put(task.id(), task); } @Override public Task find(String id) { return tasks.get(id); } @Override public void replace(Task task) { if (task == null || !tasks.containsKey(task.id())) { throw new IllegalArgumentException("existing task required"); } tasks.put(task.id(), task); } @Override public List<Task> all() { return new ArrayList<>(tasks.values()); } } import java.util.List; /** Generic reports that work for any Timed values, not only Task. */ public final class Reports { private Reports() { } /** Reads only, so it accepts a list of any Timed subtype: List<Task> included. */ public static int totalMinutes(List<? extends Timed> items) { int total = 0; for (Timed item : items) { total += item.minutes(); } return total; } /** Returns the caller's own element type, or null for an empty list. Ties keep the first. */ public static <T extends Timed> T longest(List<T> items) { T best = null; for (T item : items) { if (best == null || item.minutes() > best.minutes()) { best = item; } } return best; } } public enum Status { TODO, DONE } /** Immutable task: copies of collections can safely share these values. */ public final class Task implements Timed { private final String id; private final String title; private final int minutes; private final Status status; public Task(String id, String title, int minutes, Status status) { if (id == null || id.trim().isEmpty() || id.contains(";")) { throw new IllegalArgumentException("valid id required"); } if (title == null || title.trim().isEmpty() || title.contains(";")) { throw new IllegalArgumentException("valid title required"); } if (minutes < 1 || minutes > 240 || status == null) { throw new IllegalArgumentException("valid minutes and status required"); } this.id = id.trim(); this.title = title.trim(); this.minutes = minutes; this.status = status; } public String id() { return id; } public String title() { return title; } @Override public int minutes() { return minutes; } public Status status() { return status; } public Task withStatus(Status next) { return new Task(id, title, minutes, next); } } /** A small four-field format, deliberately not general CSV. */ public final class TaskParser { public Task parse(String line) { if (line == null) { throw new IllegalArgumentException("line required"); } String[] fields = line.split(";", -1); if (fields.length != 4) { throw new IllegalArgumentException("expected id;title;minutes;status"); } int minutes = Integer.parseInt(fields[2].trim()); Status status = Status.valueOf(fields[3].trim()); return new Task(fields[0], fields[1], minutes, status); } } import java.util.List; /** Duplicate adds and missing replacements reject before changing state. */ public interface TaskRepository { void add(Task task); Task find(String id); // Null means absent; null tasks are never stored. void replace(Task task); List<Task> all(); // A separate container in insertion order. } import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public final class TaskService { private final TaskRepository repository; private final TaskParser parser; public TaskService(TaskRepository repository, TaskParser parser) { if (repository == null || parser == null) { throw new IllegalArgumentException("dependencies required"); } this.repository = repository; this.parser = parser; } /** * Read records until EOF. Skip blanks; report rejected records with their * physical line number; retain successful records. The caller owns the * reader: this method neither closes it nor hides a read failure. */ public ImportResult importFrom(BufferedReader reader) throws IOException { List<String> errors = new ArrayList<>(); int accepted = 0; int lineNumber = 0; String line = reader.readLine(); while (line != null) { lineNumber++; if (!line.trim().isEmpty()) { try { repository.add(parser.parse(line)); accepted++; } catch (IllegalArgumentException error) { errors.add("Line " + lineNumber + ": " + error.getMessage()); } } line = reader.readLine(); } return new ImportResult(accepted, errors); } /** Convenience for in-memory records: one array element per line. */ public ImportResult importLines(String[] lines) { ImportResult result; try (BufferedReader reader = new BufferedReader(new StringReader(String.join("\n", lines)))) { result = importFrom(reader); } catch (IOException error) { throw new IllegalStateException("reading records failed", error); } return result; } /** Repeating completion is harmless. A missing ID returns false. */ public boolean complete(String id) { Task task = repository.find(id); if (task == null) { return false; } repository.replace(task.withStatus(Status.DONE)); return true; } public List<Task> openOrdered() { Comparator<Task> byMinutes = Comparator.comparingInt(Task::minutes); return repository.all().stream() .filter(task -> task.status() == Status.TODO) .sorted(byMinutes.thenComparing(Task::id)) .toList(); } public int openMinutes() { return Reports.totalMinutes(openOrdered()); } } /** Anything with a duration in minutes. Task implements it; so could a future Session. */ public interface Timed { int minutes(); }
Check your prediction
Text
Accepted: 3
Rejected: 2
C3: Write tests (20)
A1: Read chapter (25)
Open minutes: 45
Longest open: A1

The source is also available in the task-tracker download. Each editor on the site owns its own file set; an edit in one editor doesn't change another. To test your changes, make them in the editor whose entry is TrackerTest.java, or download the project and run both entries locally.

Practice with the real project

Exercise

Task Tracker: predict a new batch

Replace the lines array in Main.java with this batch, add a loop that prints every message in result.errors() right after the Rejected line, and change the completion to service.complete("I9"):

Text
D4;Plan week;30;TODO
E5;Review;30;TODO
(an empty string)
F6;Old task;15;DONE
D4;Again;10;TODO
G7;Bad minutes;300;TODO
H8;Lowercase;20;todo
I9;Quick fix;15;TODO

Before you run it, write down the full output: the two counts, each error line with its line number and message, the open tasks in order, the open minutes and the longest open task. Use the source tabs to justify every line, then run and compare. One line is the exception: when Status.valueOf gets a name that isn't a constant, its message comes from Java, not from the source tabs, so write "valueOf's message" for that line and see the exact wording when you run.

Your workspace: the task tracker Java
import java.util.ArrayList; import java.util.List; public final class ImportResult { private final int accepted; private final List<String> errors; public ImportResult(int accepted, List<String> errors) { this.accepted = accepted; this.errors = new ArrayList<>(errors); } public int accepted() { return accepted; } public List<String> errors() { return new ArrayList<>(errors); } } public class Main { public static void main(String[] args) { TaskRepository repository = new MemoryTaskRepository(); TaskService service = new TaskService(repository, new TaskParser()); String[] lines = { "B2;Practice loops;20;TODO", "bad record", "A1;Read chapter;25;TODO", "A1;Duplicate;10;TODO", "C3;Write tests;20;TODO" }; ImportResult result = service.importLines(lines); System.out.println("Accepted: " + result.accepted()); System.out.println("Rejected: " + result.errors().size()); service.complete("B2"); for (Task task : service.openOrdered()) { System.out.println(task.id() + ": " + task.title() + " (" + task.minutes() + ")"); } System.out.println("Open minutes: " + service.openMinutes()); Task longest = Reports.longest(service.openOrdered()); System.out.println("Longest open: " + longest.id()); } } import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class MemoryTaskRepository implements TaskRepository { private final Map<String, Task> tasks = new LinkedHashMap<>(); @Override public void add(Task task) { if (task == null || tasks.containsKey(task.id())) { throw new IllegalArgumentException("duplicate or missing task"); } tasks.put(task.id(), task); } @Override public Task find(String id) { return tasks.get(id); } @Override public void replace(Task task) { if (task == null || !tasks.containsKey(task.id())) { throw new IllegalArgumentException("existing task required"); } tasks.put(task.id(), task); } @Override public List<Task> all() { return new ArrayList<>(tasks.values()); } } import java.util.List; /** Generic reports that work for any Timed values, not only Task. */ public final class Reports { private Reports() { } /** Reads only, so it accepts a list of any Timed subtype: List<Task> included. */ public static int totalMinutes(List<? extends Timed> items) { int total = 0; for (Timed item : items) { total += item.minutes(); } return total; } /** Returns the caller's own element type, or null for an empty list. Ties keep the first. */ public static <T extends Timed> T longest(List<T> items) { T best = null; for (T item : items) { if (best == null || item.minutes() > best.minutes()) { best = item; } } return best; } } public enum Status { TODO, DONE } /** Immutable task: copies of collections can safely share these values. */ public final class Task implements Timed { private final String id; private final String title; private final int minutes; private final Status status; public Task(String id, String title, int minutes, Status status) { if (id == null || id.trim().isEmpty() || id.contains(";")) { throw new IllegalArgumentException("valid id required"); } if (title == null || title.trim().isEmpty() || title.contains(";")) { throw new IllegalArgumentException("valid title required"); } if (minutes < 1 || minutes > 240 || status == null) { throw new IllegalArgumentException("valid minutes and status required"); } this.id = id.trim(); this.title = title.trim(); this.minutes = minutes; this.status = status; } public String id() { return id; } public String title() { return title; } @Override public int minutes() { return minutes; } public Status status() { return status; } public Task withStatus(Status next) { return new Task(id, title, minutes, next); } } /** A small four-field format, deliberately not general CSV. */ public final class TaskParser { public Task parse(String line) { if (line == null) { throw new IllegalArgumentException("line required"); } String[] fields = line.split(";", -1); if (fields.length != 4) { throw new IllegalArgumentException("expected id;title;minutes;status"); } int minutes = Integer.parseInt(fields[2].trim()); Status status = Status.valueOf(fields[3].trim()); return new Task(fields[0], fields[1], minutes, status); } } import java.util.List; /** Duplicate adds and missing replacements reject before changing state. */ public interface TaskRepository { void add(Task task); Task find(String id); // Null means absent; null tasks are never stored. void replace(Task task); List<Task> all(); // A separate container in insertion order. } import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public final class TaskService { private final TaskRepository repository; private final TaskParser parser; public TaskService(TaskRepository repository, TaskParser parser) { if (repository == null || parser == null) { throw new IllegalArgumentException("dependencies required"); } this.repository = repository; this.parser = parser; } /** * Read records until EOF. Skip blanks; report rejected records with their * physical line number; retain successful records. The caller owns the * reader: this method neither closes it nor hides a read failure. */ public ImportResult importFrom(BufferedReader reader) throws IOException { List<String> errors = new ArrayList<>(); int accepted = 0; int lineNumber = 0; String line = reader.readLine(); while (line != null) { lineNumber++; if (!line.trim().isEmpty()) { try { repository.add(parser.parse(line)); accepted++; } catch (IllegalArgumentException error) { errors.add("Line " + lineNumber + ": " + error.getMessage()); } } line = reader.readLine(); } return new ImportResult(accepted, errors); } /** Convenience for in-memory records: one array element per line. */ public ImportResult importLines(String[] lines) { ImportResult result; try (BufferedReader reader = new BufferedReader(new StringReader(String.join("\n", lines)))) { result = importFrom(reader); } catch (IOException error) { throw new IllegalStateException("reading records failed", error); } return result; } /** Repeating completion is harmless. A missing ID returns false. */ public boolean complete(String id) { Task task = repository.find(id); if (task == null) { return false; } repository.replace(task.withStatus(Status.DONE)); return true; } public List<Task> openOrdered() { Comparator<Task> byMinutes = Comparator.comparingInt(Task::minutes); return repository.all().stream() .filter(task -> task.status() == Status.TODO) .sorted(byMinutes.thenComparing(Task::id)) .toList(); } public int openMinutes() { return Reports.totalMinutes(openOrdered()); } } /** Anything with a duration in minutes. Task implements it; so could a future Session. */ public interface Timed { int minutes(); }
Hint 1: the idea

Each line meets the same chain: TaskParser (field count, number, exact enum name), then Task's constructor (ID, title, 1 to 240), then the repository (unique ID). The first rule a line breaks decides its message. The report then filters, sorts and totals what was accepted.

Hint 2: a first step

Number the lines 1 to 8, counting the empty string as line 3. For each, find the class that rejects it, if any, and copy that class's exact message. For todo, look at how TaskParser turns the text into a Status. Then remember that openOrdered breaks ties by ID.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        TaskRepository repository = new MemoryTaskRepository();
        TaskService service = new TaskService(repository, new TaskParser());
        String[] lines = {
            "D4;Plan week;30;TODO",
            "E5;Review;30;TODO",
            "",
            "F6;Old task;15;DONE",
            "D4;Again;10;TODO",
            "G7;Bad minutes;300;TODO",
            "H8;Lowercase;20;todo",
            "I9;Quick fix;15;TODO"
        };

        ImportResult result = service.importLines(lines);
        System.out.println("Accepted: " + result.accepted());
        System.out.println("Rejected: " + result.errors().size());
        for (String error : result.errors()) {
            System.out.println(error);
        }
        service.complete("I9");
        for (Task task : service.openOrdered()) {
            System.out.println(task.id() + ": " + task.title() + " (" + task.minutes() + ")");
        }
        System.out.println("Open minutes: " + service.openMinutes());
        Task longest = Reports.longest(service.openOrdered());
        System.out.println("Longest open: " + longest.id());
    }
}

Expected output:

Text
Accepted: 4
Rejected: 3
Line 5: duplicate or missing task
Line 6: valid minutes and status required
Line 7: No enum constant Status.todo
D4: Plan week (30)
E5: Review (30)
Open minutes: 60
Longest open: D4

Line 3 is blank, so it is skipped but still counted, which is why the errors say 5, 6 and 7. Line 5 reaches MemoryTaskRepository.add and is refused there because D4 exists. 300 passes the parser but fails Task's range check. todo fails earlier, in Status.valueOf, which only knows TODO, and that exception's own message is reported. F6 is accepted but DONE, and completing I9 leaves D4 and E5, tied at 30 and ordered by ID. Reports.longest keeps the first of a tie, so D4.

Change it and test again

In the full program, change C3's duration to tie with A1. Predict the ID tie-breaker. Add an invalid line before the last valid record, and confirm it does not prevent the final import. To test an edited project file, copy that edit into the next page's test workspace before running it. Opening the next page alone only tests its original, independent source set.

Explain before moving on

Explain the path from a raw line to a displayed task. Which class owns validation? Which owns unique IDs? Why does completing B2 leave the Task object from an old snapshot unchanged?

Was this article helpful?

Your response is saved on this device.