Lesson 23 of 23

In progress

Course progress

Java

Capstone: a console task tracker

Build a small console application with a domain model, a service, a CSV store, a menu loop and tests, using everything from the track.

The last lesson in the track. You will assemble a task tracker from the pieces covered so far: records, enums, collections, exceptions, files and tests, arranged in a structure that could grow.

What you will learn

  • Model tasks as immutable records with an enum for priority.
  • Put storage behind an interface so tests need no files.
  • Wire a menu to a service without letting the menu touch persistence.

What you will build

A command-line application that:

  • Adds a task with a title and a priority.
  • Lists tasks, filtered by status.
  • Marks a task done.
  • Saves to a CSV file and loads on start.

The domain

package com.example.tasks.domain;
public enum Priority { LOW, NORMAL, URGENT }
public record Task(long id, String title, Priority priority, boolean done) {
public Task {
if (title == null || title.isBlank()) {
throw new IllegalArgumentException("title required");
}
}
Task complete() {
return new Task(id, title, priority, true);
}
}

The record is immutable, so completing a task returns a new one. That removes a class of bugs where two references disagree about whether the task is done, and it matches the value-object rule from earlier.

complete() keeps the transition inside the type. There is no setter, so no caller can flip done without going through the method — which matters once the method starts enforcing a rule.

The repository

package com.example.tasks.storage;
import com.example.tasks.domain.Task;
import java.util.List;
public interface TaskRepository {
List<Task> findAll();
void saveAll(List<Task> tasks);
}

The interface is the port. The implementation writes CSV:

package com.example.tasks.storage;
import com.example.tasks.domain.Priority;
import com.example.tasks.domain.Task;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class CsvTaskRepository implements TaskRepository {
private final Path file;
public CsvTaskRepository(String path) {
this.file = Path.of(path);
}
@Override
public List<Task> findAll() {
List<Task> tasks = new ArrayList<>();
if (!Files.exists(file)) {
return tasks;
}
try (BufferedReader reader = Files.newBufferedReader(file)) {
String line;
while ((line = reader.readLine()) != null) {
if (line.isBlank()) continue;
String[] parts = line.split(",", -1);
tasks.add(new Task(
Long.parseLong(parts[0]),
parts[1],
Priority.valueOf(parts[2]),
Boolean.parseBoolean(parts[3])));
}
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("could not read " + file.toAbsolutePath(), e);
}
return tasks;
}
@Override
public void saveAll(List<Task> tasks) {
List<String> lines = new ArrayList<>();
for (Task task : tasks) {
lines.add(task.id() + "," + task.title() + "," + task.priority() + "," + task.done());
}
try {
Files.write(file, lines);
} catch (IOException e) {
throw new IllegalStateException("could not write " + file.toAbsolutePath(), e);
}
}
}

Two decisions worth noticing. A missing file returns an empty list rather than throwing, because a first run has no data. A write failure throws a runtime exception with the absolute path, which is the message that actually helps when a path is wrong.

This format breaks if a title contains a comma. A production system would use a library or escape the field; the comment that says so is more honest than pretending the parser is general.

The service

package com.example.tasks.service;
import com.example.tasks.domain.Priority;
import com.example.tasks.domain.Task;
import com.example.tasks.storage.TaskRepository;
import java.util.List;
public class TaskService {
private final TaskRepository repository;
private List<Task> tasks;
public TaskService(TaskRepository repository) {
this.repository = repository;
this.tasks = repository.findAll();
}
public Task add(String title, Priority priority) {
long nextId = tasks.stream().mapToLong(Task::id).max().orElse(0L) + 1;
Task task = new Task(nextId, title.strip(), priority, false);
tasks.add(task);
repository.saveAll(tasks);
return task;
}
public boolean complete(long id) {
for (int i = 0; i < tasks.size(); i++) {
if (tasks.get(i).id() == id) {
tasks.set(i, tasks.get(i).complete());
repository.saveAll(tasks);
return true;
}
}
return false;
}
public List<Task> list(boolean onlyOpen) {
return onlyOpen ? tasks.stream().filter(t -> !t.done()).toList() : List.copyOf(tasks);
}
}

The service owns the list and saves after every change, so a crash loses at most the action in flight. complete returns whether it found the task, which lets the menu print an honest message instead of pretending.

list returns an immutable copy. A caller cannot remove a task by mutating the returned list, which keeps the save-after-change rule true.

The menu

package com.example.tasks.cli;
import com.example.tasks.domain.Priority;
import com.example.tasks.service.TaskService;
import java.util.Scanner;
public class Menu {
private final TaskService service;
private final Scanner in = new Scanner(System.in);
public Menu(TaskService service) {
this.service = service;
}
public void run() {
while (true) {
System.out.print("[a]dd [l]ist [d]one [q]uit: ");
String choice = in.nextLine().strip().toLowerCase();
switch (choice) {
case "a" -> add();
case "l" -> list();
case "d" -> done();
case "q" -> { return; }
default -> System.out.println("unknown command");
}
}
}
private void add() {
System.out.print("title: ");
String title = in.nextLine();
System.out.print("priority (low/normal/urgent): ");
String raw = in.nextLine().strip().toUpperCase();
try {
Priority priority = Priority.valueOf(raw);
var task = service.add(title, priority);
System.out.println("added #" + task.id());
} catch (IllegalArgumentException e) {
System.out.println("invalid priority or title");
}
}
private void list() {
var tasks = service.list(true);
if (tasks.isEmpty()) {
System.out.println("nothing open");
return;
}
tasks.forEach(t -> System.out.println("#" + t.id() + " [" + t.priority() + "] " + t.title()));
}
private void done() {
System.out.print("id: ");
try {
long id = Long.parseLong(in.nextLine().strip());
System.out.println(service.complete(id) ? "completed" : "no such task");
} catch (NumberFormatException e) {
System.out.println("enter a number");
}
}
}

The menu parses input and prints; it decides nothing. Every rule lives in the domain or the service, which is why the same service could back a web interface tomorrow.

Wiring

package com.example.tasks;
import com.example.tasks.cli.Menu;
import com.example.tasks.service.TaskService;
import com.example.tasks.storage.CsvTaskRepository;
public class App {
public static void main(String[] args) {
var repository = new CsvTaskRepository("data/tasks.csv");
var service = new TaskService(repository);
new Menu(service).run();
}
}

Four lines. The wiring is the only place that knows all three layers, which is what makes the dependencies visible.

Tests

import com.example.tasks.domain.Priority;
import com.example.tasks.domain.Task;
import com.example.tasks.service.TaskService;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class TaskServiceTest {
@Test
void completingAnUnknownIdReturnsFalse() {
var repo = new InMemoryRepository();
var service = new TaskService(repo);
assertFalse(service.complete(99));
}
@Test
void addAssignsIncreasingIds() {
var service = new TaskService(new InMemoryRepository());
assertEquals(1, service.add("first", Priority.LOW).id());
assertEquals(2, service.add("second", Priority.LOW).id());
}
static class InMemoryRepository implements com.example.tasks.storage.TaskRepository {
private final List<Task> tasks = new ArrayList<>();
public List<Task> findAll() { return List.copyOf(tasks); }
public void saveAll(List<Task> tasks) { this.tasks.clear(); this.tasks.addAll(tasks); }
}
}

The in-memory repository is four lines and removes the filesystem from the tests, which is the payoff of the port. Both tests are fast, deterministic and name the rule they check.

Review checklist

  1. Add a task, quit, restart, and confirm it loaded.
  2. Complete a task and confirm the file changed.
  3. Enter a bad priority and confirm the app keeps running.
  4. Delete the data file and confirm the app starts with an empty list.
  5. Run the tests with mvn test or gradle test.

Letting the menu call the repository directly. The save-after-change rule then lives in two places, and one of them will be forgotten. The service owns persistence; the menu asks the service.

Add a remove(long id) method to the service and a [r]emove command to the menu, keeping the menu free of storage knowledge.

Show solution
public boolean remove(long id) { boolean removed = tasks.removeIf(task -> task.id() == id); if (removed) { repository.saveAll(tasks); } return removed; }

In the menu, prompt for the id, parse it with the same guard as done, call service.remove(id), and print a message based on the boolean. The service decides and persists; the menu only reads input and prints, so a change to the storage format never reaches the CLI.

Where to go next

You have finished the Java track. Useful next steps: JDBC or an ORM for a real database, a small HTTP layer with the built-in server, and reading the standard library’s source. The structure you built here — domain, service, ports, thin entry point — is the same shape a larger application uses.

Recap

  • Model values as immutable records and keep transitions on the type.
  • Put the storage behind an interface so tests need no files.
  • Keep the menu and main thin, and save through the service after every change.

Why save after every change?
It keeps the file consistent with memory, so a crash loses nothing. Batching is faster and riskier.
How would this become a web app?
Replace the menu with request handlers that call the same service, and change only `App`’s wiring.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.