The capstone for this tutorial is a library management command line program. You add the books, you register the members, you borrow and you return, and you see what is on the loan. It is deliberately small, but it is complete. There is a model, there is a service with the rules, there is a user interface, there is the persistence, and there is a set of the tests. That combination is what turns "a few Java files" into a program that you would be happy to hand to somebody else.
The previous lesson in this module covered "How Do You Structure a Small Multi-Class Java Program?", and this lesson is the last one in the Java Projects and Build Tools module.
What is the shape of the project?
Look at the layout before the code.
library/
src/
main/
java/
com/tutorsbot/library/
Main.java
model/
Book.java
Member.java
Loan.java
service/
LibraryService.java
LoanPolicy.java
io/
BookRepository.java
ConsoleMenu.java
test/
java/
com/tutorsbot/library/
service/
LibraryServiceTest.javaThere are three packages again, plus the tests. The model holds Book, Member and Loan. The service holds the rules and the loan policy. The io package holds the repository that reads and writes the catalogue, and the console menu that talks to the user. The test tree mirrors the main tree exactly, which is the convention for every build tool.
How should the model be written?
With the records and with the validation in the compact constructor.
package com.tutorsbot.library.model;
public record Book(String isbn, String title, String author) {
public Book {
if (isbn == null || isbn.isBlank()) {
throw new IllegalArgumentException("isbn is required");
}
if (title == null || title.isBlank()) {
throw new IllegalArgumentException("title is required");
}
}
public static void main(String[] args) {
Book book = new Book("978-3", "Clean Code", "Robert Martin");
System.out.println("book : " + book);
try {
new Book(" ", "No title", "Nobody");
} catch (IllegalArgumentException e) {
System.out.println("rejected : " + e.getMessage());
}
}
}The output is this.
book : Book[isbn=978-3, title=Clean Code, author=Robert Martin]
rejected : isbn is requiredThe model is deliberately tiny and deliberately strict. An invalid Book or Member cannot be created, so every later piece of the code can assume that the fields are present. In a real project you would add a few more fields, such as a publication year or an email address, but the shape does not change.
Where do the rules live?
All of them in the service. The service is the only class that knows how many loans a member may have, that a book can only be on one loan, and that both the book and the member must exist.
package com.tutorsbot.library.service;
import com.tutorsbot.library.model.Book;
import com.tutorsbot.library.model.Member;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class LibraryService {
private final Map<String, Book> books = new HashMap<>();
private final Map<String, Member> members = new HashMap<>();
private final Map<String, String> loans = new HashMap<>();
private final int maxLoans;
public LibraryService(int maxLoans) {
this.maxLoans = maxLoans;
}
public void addBook(Book book) {
books.put(book.isbn(), book);
}
public void register(Member member) {
members.put(member.id(), member);
}
public Optional<Book> findBook(String isbn) {
return Optional.ofNullable(books.get(isbn));
}
public boolean borrow(String isbn, String memberId) {
if (!books.containsKey(isbn) || !members.containsKey(memberId)) {
return false;
}
if (loans.containsKey(isbn)) {
return false;
}
long active = loans.values().stream().filter(id -> id.equals(memberId)).count();
if (active >= maxLoans) {
return false;
}
loans.put(isbn, memberId);
return true;
}
public boolean giveBack(String isbn) {
return loans.remove(isbn) != null;
}
public Map<String, String> activeLoans() {
return Map.copyOf(loans);
}
public int bookCount() {
return books.size();
}
}The output of that service is this.
books : 2
borrow known : true
borrow again : false
unknown book : false
unknown member: false
loans : {978-1=M-1}
give back : true
give back twice : falseRead the method borrow and you can see the whole rule set in one place. An unknown book or member is refused, a book that is already on the loan is refused, and a member that is at the limit is refused. Every refusal returns false rather than throwing, because "no" is an expected answer here and not an error.
There are two small design points that are worth copying. The loans are held in a Map from the isbn to the member id, which makes the question of whether this book is on the loan a single lookup rather than a scan. And the method activeLoans returns Map.copyOf, so that a caller cannot modify the internal state of the service by accident.
What does the user interface look like?
A menu loop. The console class knows about the service and nothing else, and it receives its scanner through the constructor, so that a test can feed it the input.
package com.tutorsbot.library.io;
import com.tutorsbot.library.model.Book;
import com.tutorsbot.library.service.LibraryService;
import java.util.Map;
import java.util.Scanner;
public class ConsoleMenu {
private final LibraryService service;
private final Scanner scanner;
public ConsoleMenu(LibraryService service, Scanner scanner) {
this.service = service;
this.scanner = scanner;
}
public void printMenu() {
System.out.println("1) add book 2) borrow 3) return 4) list loans 5) quit");
}
public int readChoice() {
String line = scanner.nextLine().trim();
try {
return Integer.parseInt(line);
} catch (NumberFormatException e) {
return -1;
}
}
public boolean handle(int choice) {
switch (choice) {
case 1 -> {
System.out.print("isbn: ");
String isbn = scanner.nextLine().trim();
System.out.print("title: ");
String title = scanner.nextLine().trim();
System.out.print("author: ");
String author = scanner.nextLine().trim();
service.addBook(new Book(isbn, title, author));
System.out.println("added " + isbn);
}
case 2 -> {
System.out.print("isbn: ");
String isbn = scanner.nextLine().trim();
System.out.print("member id: ");
String memberId = scanner.nextLine().trim();
System.out.println(service.borrow(isbn, memberId) ? "borrowed" : "cannot borrow");
}
case 3 -> {
System.out.print("isbn: ");
String isbn = scanner.nextLine().trim();
System.out.println(service.giveBack(isbn) ? "returned" : "not on loan");
}
case 4 -> {
for (Map.Entry<String, String> entry : service.activeLoans().entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
case 5 -> {
return false;
}
default -> System.out.println("unknown choice");
}
return true;
}
}The output is this.
1) add book 2) borrow 3) return 4) list loans 5) quit
isbn: title: author: added 978-1
1) add book 2) borrow 3) return 4) list loans 5) quit
isbn: member id: borrowed
1) add book 2) borrow 3) return 4) list loans 5) quit
978-1 -> M-1
1) add book 2) borrow 3) return 4) list loans 5) quit
loans at the end : {978-1=M-1}The switch expression keeps each option short, and the method returns a boolean so that the loop can ask whether to continue. Everything that the user types is trimmed, and every branch handles the case where the input does not make sense. The default branch prints "unknown choice" instead of crashing.
Notice that the choice is read with readChoice, which parses a whole line rather than calling nextInt directly. Mixing nextInt with nextLine on the same scanner leaves the newline behind, and the next line that you read comes back empty. Reading the choice as a line avoids that trap entirely. The demo at the end drives that menu with a scripted scanner, which is exactly how you would test it. You feed the input, and you assert on what was printed.
What about saving the data?
A real version needs the catalogue to survive a restart. The class BookRepository in the io package is the right home for that. It reads and writes a file using java.nio.file, and it converts between the text format and the Book records. Because it lives in io, the service never learns that a file exists. You swap it for an in-memory implementation and the service is unchanged.
There are two rules that make it robust. You write to a temporary file and you move it into the place, so that a crash cannot leave a half-written catalogue. And you treat a missing file as an empty catalogue rather than as an error, so that the first run works.
What should the tests cover?
You start with the service, because that is where the rules are.
- Adding a book makes it findable by isbn.
- Borrowing a book that does not exist returns false.
- Borrowing a book that is already out returns false.
- A member at the loan limit is refused.
- Returning a book frees it, and returning it twice fails.
- An invalid book or member is rejected at construction.
Those six cases cover the whole rule set. You write them, and then you can refactor the service with confidence, which is the point of the exercise.
What does the capstone teach?
Every technique in the tutorial appears here in a realistic shape. There are the records for the data, the validation at the construction, a service that holds the rules and returns the results instead of printing them, an io layer that owns the outside world, the dependency injection through the constructors so that the pieces can be tested, the defensive copies on the way out, and a test suite that pins the rules down.
If you build it, you run it, and then you change one rule, such as allowing the three loans instead of the two, the tests will tell you immediately whether the change did what you meant. That feedback loop is the thing that is worth taking away from the whole tutorial.
The habits to keep
- Keep the rules in the service and the words in the interface.
- Return the results from the service, and let the caller decide how to present them.
- Validate the data once, at the construction, and trust it afterwards.
- Inject the scanner and the repository, so that everything can be tested.
- Test the rules, and not the formatting.
- Make the first version work end to end before you add the features.
Try it yourself: build the program in the stages. First the model and the service with a main that calls them directly, and write the six tests above. Then add the console menu. Then add the file repository and make the catalogue survive a restart. After each stage, run the tests, and finish by adding a feature of your own, such as a due date and an overdue list, making sure that the existing tests still pass without being edited.