ShopLite console app: structure and plan
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite has more than twenty menu items. If every menu method opened connections, built SQL and checked rules, one change would break many screens and nothing could be tested without MySQL.
The finished app: feature list and menu tree
A feature list is a short list of what the finished app must do, written before any code. It shows which screens you need, which service method each one calls and which tables each one touches.
Example 1 starts the finished ShopLite console app and walks through its menus.
Example 1 · Running the finished app
Runs in: the finished shoplite-console project with the ShopLite database
# macOS Terminal or Git Bash. Windows Command Prompt: set DB_USER=shoplite_app (and so on)export DB_URL=jdbc:mysql://localhost:3306/shopliteexport DB_USER=shoplite_appexport DB_PASSWORD=your-passwordjava -jar target/shoplite-console-1.0.0.jarShopLite console 1.0.0 - MySQL 9.4.0, pool size 5 === ShopLite === 1. Products and categories 2. Customers 3. Orders 4. Reports 0. Exit Choose: 1 === Products and categories === 1. List products 2. Search products 3. Add product 4. Edit product 5. Adjust stock 6. Remove product 7. List categories 8. Add category 9. Rename category 0. Back Choose: 0 === ShopLite === 1. Products and categories 2. Customers 3. Orders 4. Reports 0. Exit Choose: 2 === Customers === 1. List customers 2. Register customer 3. Update customer 4. Show customer and addresses 5. Add address 0. Back Choose: 0 === ShopLite === 1. Products and categories 2. Customers 3. Orders 4. Reports 0. Exit Choose: 0 Goodbye.
What this code does
- The JAR comes from
mvn packagein the last milestone; until then,mvn compile exec:javastarts the sameMain. - The first line is printed by
Mainonce the pool is open. Your MySQL version will differ (8.4 for most learners). - Every submenu ends with
0. Backand only the main menu has0. Exit, so the user always knows the way out.
ShopLite console has four areas, and the menu tree follows them:
- Products and categories: list (paged), search, add, edit, adjust stock, remove; list, add and rename categories
- Customers: list, register, update, show with addresses, add an address
- Orders: new order from a cart, order history, show, mark shipped, mark delivered, cancel
- Reports: revenue by day, top products, sales by category, customers who never ordered, low-stock alert
Each menu item becomes one small method in a screen and usually one method in a service. The three milestone projects of this module build the areas in that order: catalog and customers, then orders, then reports and the release. Without a feature list, apps grow by accident: two screens that do almost the same thing, and a missing one you find only during a demo.
Packages and the dependency rule
The dependency rule says a layer may call only the layer below it: app, then service, then dao, then MySQL. model holds plain records that every layer may use, and config builds the settings and the pool once at startup.
Example 2 puts four layers in one file: model, dao, service and app. Only the app layer prints, and the service never touches SQL.
Example 2 · Four layers in one file
import java.math.BigDecimal;import java.util.HashMap;import java.util.Map;import java.util.Optional;
// model: plain data. Depends on nothing.record Product(int id, String name, BigDecimal price, int stock) {}
// dao: how products are stored. No rules, no printing.interface ProductDao { Optional<Product> findById(int id);
void save(Product product);}
class InMemoryProductDao implements ProductDao { private final Map<Integer, Product> rows = new HashMap<>();
public Optional<Product> findById(int id) { return Optional.ofNullable(rows.get(id)); }
public void save(Product product) { rows.put(product.id(), product); }}
// service: the rules. Talks to the dao interface, never prints.class ValidationException extends RuntimeException { ValidationException(String message) { super(message); }}
class CatalogService { private final ProductDao products;
CatalogService(ProductDao products) { this.products = products; }
Product changePrice(int id, BigDecimal newPrice) { if (newPrice.signum() <= 0) { throw new ValidationException("Price must be more than 0"); } Product old = products.findById(id) .orElseThrow(() -> new ValidationException("Product " + id + " not found")); Product changed = new Product(old.id(), old.name(), newPrice, old.stock()); products.save(changed); return changed; }}
public class LayersDemo { public static void main(String[] args) { ProductDao dao = new InMemoryProductDao(); dao.save(new Product(1, "Redmi Note 13 5G", new BigDecimal("17999.00"), 40)); CatalogService catalog = new CatalogService(dao);
tryChange(catalog, 1, "16999.00"); tryChange(catalog, 1, "0"); tryChange(catalog, 9, "499.00"); }
static void tryChange(CatalogService catalog, int id, String price) { try { Product p = catalog.changePrice(id, new BigDecimal(price)); System.out.println("Saved: " + p.name() + " now costs Rs. " + p.price()); } catch (ValidationException e) { System.out.println("Error: " + e.getMessage()); } }}Saved: Redmi Note 13 5G now costs Rs. 16999.00 Error: Price must be more than 0 Error: Product 9 not found
What this code does
- The comment lines mark the layers; in ShopLite each one is a package. Only
LayersDemo, the app layer, prints anything. CatalogServicereceives theProductDaointerface, so here it gets the in-memory one and in ShopLite the JDBC one, with no change to the rule.- The service reports a broken rule by throwing
ValidationException; the app layer turns it into anError:line.
Without the rule, one menu method opens a connection, builds SQL, checks the stock and prints, all together. The next screen that places orders copies that code, a bug fix lands in one copy only, and nothing can be tested without MySQL. With layers, the stock rule lives once in OrderService, and the web API in the next section calls the same service with no Scanner in sight. Two checks keep the rule honest: a service never prints or reads input, and a DAO never decides a business rule such as "price must be more than 0". In an interview, say it in one line: screens or controllers handle input and output, services own rules and transactions, DAOs own SQL. The packages are:
app:Main,Menu,ConsoleIOand one screen per area (CatalogScreen,CustomerScreen,OrderScreen,ReportScreen)service:CatalogService,CustomerService,OrderService,ReportServiceand theShopExceptiontypesdao: interfaces such asProductDao, theirJdbc...classes,Databaseand theDataAccessExceptiontypesmodelandconfig: records such asProduct,PageandCart;AppConfigandDataSourceFactory
From the module projects to this structure. The app from the connection-pooling module already has these layers, so this module keeps its packages and replaces a few classes with designs that scale to more than twenty menu items. Make the changes at the start of the first milestone project and run the app after each one:
JdbcTransactionManagerandConnectionLeasebecome oneDatabaseclass. It still implementsTransactionManager, but DAOs calldb.run("action", connection -> ...)andSqlErrorstranslates everySQLExceptionin one place, so the same try/catch disappears from every DAO method.ConsoleMenubecomesMenu,ConsoleIOand one screen per area, because one menu class with every option would grow to hundreds of lines.ProductServicebecomesCatalogService, since it now owns categories too.- The exceptions are regrouped by what the caller does with them:
ValidationException,NotFoundException,ConflictExceptionandOutOfStockException(allShopException) replaceInvalidInputException,ProductNotFoundException,CustomerNotFoundExceptionandEmailAlreadyUsedException. Indao,DuplicateKeyException,ForeignKeyExceptionandTransientDataAccessExceptionreplaceDuplicateEmailException, so one rule covers every unique column. AppConfiggets simpler:db.pool.max-sizebecomesdb.pool.size(DB_POOL_SIZE), the timeout moves intoDataSourceFactory,app.page.sizeandapp.low.stock.thresholdare added,SettingsReaderis folded in, andapplication.propertiesmoves fromsrc/main/resourcesto the folder you run the app from, so the runnable JAR is configured without a rebuild.StartupExceptionstays.db.init,DatabaseInitializerandSqlScriptgive way todb/shoplite.sqland setup scripts, because a released app should not create tables at every start.RowMapperfrom the catalog-reports project returns inJdbcReportDao, renamed frommapRowtomap.- Everything else (the
modelrecords, the DAO interfaces,DataSourceFactory, and the pom with mysql-connector-j 26.7.0, HikariCP 7.1.0 and JUnit 5.14.4) carries on as it is.
Find the bug
Find the layer mistake
Each snippet breaks the dependency rule. Find the line that is in the wrong layer.
This method belongs to CatalogService.
Round 1 of 2Wiring everything once in Main
Constructor injection means handing an object the things it needs through its constructor, instead of letting it create them inside. CatalogService receives a ProductDao and never writes new JdbcProductDao(...).
Main wires in layer order: load AppConfig, open the HikariCP pool, wrap it in one Database, then build the DAOs, the services, the screens and the main menu. Example 3 is the real Main.
Example 3 · src/main/java/com/shoplite/app/Main.java
Runs in: the shoplite-console project
package com.shoplite.app;
import com.shoplite.config.AppConfig;import com.shoplite.config.DataSourceFactory;import com.shoplite.config.StartupException;import com.shoplite.dao.AddressDao;import com.shoplite.dao.CategoryDao;import com.shoplite.dao.CustomerDao;import com.shoplite.dao.Database;import com.shoplite.dao.JdbcAddressDao;import com.shoplite.dao.JdbcCategoryDao;import com.shoplite.dao.JdbcCustomerDao;import com.shoplite.dao.JdbcOrderDao;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.JdbcReportDao;import com.shoplite.dao.OrderDao;import com.shoplite.dao.ProductDao;import com.shoplite.service.CatalogService;import com.shoplite.service.CustomerService;import com.shoplite.service.OrderService;import com.shoplite.service.ReportService;import com.zaxxer.hikari.HikariDataSource;import javax.sql.DataSource;
/** Starts ShopLite: configuration, pool, then every object wired once, in layer order. */public final class Main {
public static final String VERSION = "1.0.0";
private Main() { }
public static void main(String[] args) { try { AppConfig config = AppConfig.load(); try (HikariDataSource dataSource = DataSourceFactory.create(config)) { // the pool closes on exit run(config, dataSource, ConsoleIO.system()); } } catch (StartupException e) { System.err.println("ShopLite could not start: " + e.getMessage()); System.exit(1); } }
public static void run(AppConfig config, DataSource dataSource, ConsoleIO io) { // dao layer: one Database shared by every DAO Database db = new Database(dataSource); CategoryDao categoryDao = new JdbcCategoryDao(db); ProductDao productDao = new JdbcProductDao(db); CustomerDao customerDao = new JdbcCustomerDao(db); AddressDao addressDao = new JdbcAddressDao(db); OrderDao orderDao = new JdbcOrderDao(db);
// service layer: rules, given their DAOs through the constructor CatalogService catalog = new CatalogService(categoryDao, productDao); CustomerService customers = new CustomerService(customerDao, addressDao); OrderService orders = new OrderService(db, customerDao, addressDao, productDao, orderDao); ReportService reports = new ReportService(new JdbcReportDao(db), productDao, customerDao, config.lowStockThreshold());
Menu mainMenu = new Menu("ShopLite", "Exit", io) .add("Products and categories", new CatalogScreen(catalog, io, config.pageSize()).menu()::run) .add("Customers", new CustomerScreen(customers, io, config.pageSize()).menu()::run) .add("Orders", new OrderScreen(orders, catalog, customers, io).menu()::run) .add("Reports", new ReportScreen(reports, io).menu()::run);
String mysql = db.run("check connection", c -> c.getMetaData().getDatabaseProductVersion()); io.println("ShopLite console " + VERSION + " - MySQL " + mysql + ", pool size " + config.poolSize()); try { mainMenu.run(); } catch (InputClosedException e) { io.println(""); } io.println("Goodbye."); }}ShopLite console 1.0.0 - MySQL 9.4.0, pool size 5 === ShopLite === 1. Products and categories 2. Customers 3. Orders 4. Reports 0. Exit Choose: 0 Goodbye.
What this code does
runis separate frommain, so a test or another front end can wire the same objects with a differentConsoleIOorDataSource.OrderServicegetsdbas itsTransactionManager: the sameDatabasegives DAOs their connections and runs transactions, so inside an order every DAO uses one connection.- The
InputClosedExceptioncatch is the only place where an exception ends the menu on purpose: the input ended, nothing broke.
Because objects arrive through constructors, a test can pass an in-memory DAO, and the app has exactly one pool. The bug it prevents is common: a DAO that builds its own HikariDataSource, so five DAOs open five pools and a transaction cannot share one connection across them.
main also owns startup and shutdown. The pool is opened in try-with-resources, so it closes when the user picks Exit. A StartupException (a missing setting, a wrong password, MySQL not running) prints one clear line and exits with code 1 instead of a stack trace.
Order of execution
Order the wiring in Main
Tap the steps Main takes, from first to last.
A menu loop with small command handlers
A command handler is one small method per menu item, such as addProduct() or cancel(). A Menu keeps label and handler pairs, prints them with numbers, reads the choice and runs the chosen handler.
Example 4 is a small Menu that holds its handlers as Runnables, so this::addProduct fits. It runs a scripted session: a good choice, a bad number and a failing action.
Example 4 · A Menu of small handlers
import java.io.BufferedReader;import java.io.IOException;import java.io.StringReader;import java.util.ArrayList;import java.util.List;
class ShopException extends RuntimeException { ShopException(String message) { super(message); }}
class Menu { private record Option(String label, Runnable action) { }
private final String title; private final BufferedReader in; private final List<Option> options = new ArrayList<>();
Menu(String title, BufferedReader in) { this.title = title; this.in = in; }
Menu add(String label, Runnable action) { options.add(new Option(label, action)); return this; }
void run() throws IOException { while (true) { System.out.println("=== " + title + " ==="); for (int i = 0; i < options.size(); i++) { System.out.println((i + 1) + ". " + options.get(i).label()); } System.out.println("0. Exit"); String line = in.readLine(); System.out.println("Choose: " + line); // echo the typed line, as a terminal shows it if (line == null || line.equals("0")) { return; } int choice = line.matches("\\d+") ? Integer.parseInt(line) : -1; if (choice < 1 || choice > options.size()) { System.out.println("Please enter a number from 0 to " + options.size() + "."); continue; } try { options.get(choice - 1).action().run(); } catch (ShopException e) { // one failed action must not end the app System.out.println("Error: " + e.getMessage()); } } }}
public class MenuDemo { static void listProducts() { System.out.println(" MOB-RN13 Redmi Note 13 5G Rs. 17,999.00"); }
static void placeOrder() { throw new ShopException("Out of stock: Logitech M331 Silent Mouse"); }
public static void main(String[] args) throws IOException { BufferedReader typed = new BufferedReader(new StringReader("1\n7\n2\n0\n")); new Menu("ShopLite", typed) .add("List products", MenuDemo::listProducts) .add("Place order", MenuDemo::placeOrder) .run(); System.out.println("Goodbye."); }}=== ShopLite === 1. List products 2. Place order 0. Exit Choose: 1 MOB-RN13 Redmi Note 13 5G Rs. 17,999.00 === ShopLite === 1. List products 2. Place order 0. Exit Choose: 7 Please enter a number from 0 to 2. === ShopLite === 1. List products 2. Place order 0. Exit Choose: 2 Error: Out of stock: Logitech M331 Silent Mouse === ShopLite === 1. List products 2. Place order 0. Exit Choose: 0 Goodbye.
What this code does
- A
StringReaderstands in for the keyboard, and the loop printsChoose:with the typed line, so the run reads like a terminal session. 7is outside 0 to 2, so the menu explains the range and shows itself again.placeOrderthrowsShopException; the loop printsError: ...and keeps going.- ShopLite's
Menuis the same class with aConsoleIOinstead of the reader and a secondcatchforDataAccessException.
The alternative is one giant switch with all the code inside the cases. It is fine for three items, but ShopLite has more than twenty: the method grows to hundreds of lines, variables leak from one case to the next, and every new feature means editing the biggest method in the app. With a Menu, a new feature is one add("label", this::handler) line plus one method.
The loop also owns error handling, in one place. A ShopException ("Out of stock", "Customer 99 not found") prints Error: ... and the menu carries on; a DataAccessException prints a database message. Any other exception is a bug, so it is not caught: you want to see it while testing, not hide it.
Fix the error
Fix the menu loop
Read the real error, then pick the line that fixes it.
The app crashes when the input ends, for example at the end of a piped file.
Error
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "line" is null
Input helpers shared by every screen
ConsoleIO is the one class that reads the keyboard and prints. Its helpers, such as readInt(prompt, min, max), ask again until the value is valid, so no screen parses numbers by itself.
Example 5 shows the one read loop behind every helper, used once with a number check and once with a PIN code check.
Example 5 · One read loop for every kind of input
import java.io.BufferedReader;import java.io.IOException;import java.io.StringReader;import java.io.UncheckedIOException;import java.util.function.Function;
class ValidationException extends RuntimeException { ValidationException(String message) { super(message); }}
class Input { private final BufferedReader in;
Input(BufferedReader in) { this.in = in; }
String readLine(String prompt) { System.out.print(prompt); try { String line = in.readLine(); System.out.println(line); // echo: the StringReader plays the keyboard return line.trim(); } catch (IOException e) { throw new UncheckedIOException(e); } }
// Asks again until the check accepts the text <T> T read(String prompt, Function<String, T> check) { while (true) { try { return check.apply(readLine(prompt)); } catch (ValidationException e) { System.out.println(" " + e.getMessage()); } } }
int readInt(String prompt, int min, int max) { return read(prompt, text -> { if (text.matches("-?\\d{1,9}")) { int value = Integer.parseInt(text); if (value >= min && value <= max) { return value; } } throw new ValidationException("Please enter a whole number from " + min + " to " + max + "."); }); }}
public class InputDemo { static String pincode(String text) { if (!text.matches("[1-9][0-9]{5}")) { throw new ValidationException("PIN code must be 6 digits and must not start with 0"); } return text; }
public static void main(String[] args) { Input io = new Input(new BufferedReader(new StringReader("two\n12\n3\n56001\n560038\n"))); int quantity = io.readInt("Quantity: ", 1, 10); String pin = io.read("PIN code: ", InputDemo::pincode); System.out.println("Got quantity " + quantity + " and PIN code " + pin); }}Quantity: two Please enter a whole number from 1 to 10. Quantity: 12 Please enter a whole number from 1 to 10. Quantity: 3 PIN code: 56001 PIN code must be 6 digits and must not start with 0 PIN code: 560038 Got quantity 3 and PIN code 560038
What this code does
read(prompt, check)is the only loop:readIntand the PIN code check reuse it by passing a different check.- A check rejects a value by throwing
ValidationException; the loop prints the message and asks again, so the caller only ever gets a valid value. pincodeplays the part ofCustomerService.pincode: the rule lives in the service, and the screen borrows it for an early re-prompt.
Two kinds of checks meet here. Format checks (is it a number, a date, y or n?) live in ConsoleIO. Rule checks (is this a valid email or a 6-digit PIN code?) live in the service, as public methods such as CustomerService.email(text). A screen passes them to read(...) to re-prompt early, and the service checks again when it saves, because a web API will call the service without any screen.
When input ends, readLine() returns null: Ctrl+D on macOS, Ctrl+Z then Enter on Windows, or the end of a piped file. A loop that ignores this spins forever on null. ConsoleIO throws InputClosedException instead, and Main treats it like Exit.
Predict the output
Predict the end of input
The reader holds one line. What does the second readLine() return?
Next step
Check your understanding
11 quick questions