Lesson 5 of 6
CLI Application Architecture
A well-designed CLI application separates command parsing, business logic, and output. The Command pattern + a dispatch table create a clean, extensible CLI architecture. This is the backbone of tools like Maven, Git, and Docker CLI.
CLI Design - Command Dispatch
import java.util.*;
import java.util.function.*;
// Named command with description
record CliCommand(String name, String description, Consumer<String[]> handler) {}
public class LibraryCli {
private final LibraryService service;
private final Map<String, CliCommand> commands = new LinkedHashMap<>();
private boolean running = true;
public LibraryCli(LibraryService service) {
this.service = service;
registerCommands();
}
private void registerCommands() {
register("add", "add <isbn> <title> <author> <price> - Add a book",
args -> addBook(args));
register("search", "search <query> - Search by title",
args -> search(args));
register("borrow", "borrow <isbn> <memberId> - Check out a book",
args -> borrowBook(args));
register("return", "return <isbn> - Return a book",
args -> returnBook(args));
register("list", "list - List all books",
args -> listBooks());
register("help", "help - Show commands",
args -> printHelp());
register("exit", "exit - Quit",
args -> running = false);
}
private void register(String name, String description, Consumer<String[]> handler) {
commands.put(name, new CliCommand(name, description, handler));
}
public void run() {
System.out.println("=== Library Management System ===");
System.out.println("Type 'help' for available commands.\n");
Scanner scanner = new Scanner(System.in);
while (running && scanner.hasNextLine()) {
System.out.print("> ");
String line = scanner.nextLine().trim();
if (line.isBlank()) continue;
String[] parts = line.split("\\s+", 2); // split on first space only
String verb = parts[0].toLowerCase();
String[] args = parts.length > 1 ? parts[1].split("\\s+") : new String[0];
CliCommand cmd = commands.get(verb);
if (cmd == null) {
System.err.println("Unknown command: '" + verb + "'. Type 'help'.");
} else {
try {
cmd.handler().accept(args);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
System.out.println("Goodbye!");
}
private void addBook(String[] args) {
if (args.length < 4) { System.err.println("Usage: add <isbn> <title> <author> <price>"); return; }
service.addBook(new Book(args[0], args[1], args[2], Double.parseDouble(args[3])));
System.out.println("✓ Added: " + args[1]);
}
private void search(String[] args) {
if (args.length < 1) { System.err.println("Usage: search <query>"); return; }
List<Book> results = service.searchByTitle(args[0]);
if (results.isEmpty()) { System.out.println("No results."); return; }
results.forEach(b -> System.out.printf(" [%-10s] %s - $%.2f%n", b.getIsbn(), b.getTitle(), b.getPrice()));
}
private void borrowBook(String[] args) {
if (args.length < 2) { System.err.println("Usage: borrow <isbn> <memberId>"); return; }
service.checkout(args[0], args[1]);
System.out.println("✓ Checked out successfully");
}
private void returnBook(String[] args) {
if (args.length < 1) { System.err.println("Usage: return <isbn>"); return; }
service.returnBook(args[0]);
System.out.println("✓ Returned successfully");
}
private void listBooks() { service.getAllBooks().forEach(b -> System.out.println(" " + b)); }
private void printHelp() { System.out.println("Available commands:"); commands.values().forEach(c -> System.out.println(" " + c.description())); }
public static void main(String[] args) {
LibraryService service = new LibraryService(new InMemoryBookRepository());
new LibraryCli(service).run();
}
}Quick Quiz
Tip
Tip
Practice CLI Application Architecture in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for CLI Application Architecture
Practice Task
Note
Practice Task - (1) Write a working example of CLI Application Architecture from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with CLI Application Architecture is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?