A small Java program still has a shape. The model package holds the data, the service package holds the logic, and the io package holds everything that touches the outside world. The entry point wires them together. Get that shape right in a program of five classes and you will not need to relearn it in a program of five hundred.
The previous lesson in this module covered "What Do Maven and Gradle Do For Your Projects?", and the next lesson in this module is about "What Goes Into a Complete Library Management CLI Project?".
What are the basic rules?
There is one public class per file, and the file name matches the class name. The package declaration matches the directory that the file sits in. The entry point is a class with a main method, and it is the only class that knows about all the others. The classes inside a package see each other without the imports, and the classes in the other packages need an import. You keep the fields private and you expose the behaviour through the methods.
- One public class per file, and the file name matches the class name.
- The package declaration matches the directory the file sits in.
- The entry point is a class with a main method, and it is the only class that knows about all the others.
- Classes inside a package see each other without imports; classes in other packages need an import.
- Keep fields private and expose behaviour through methods.
The first rule catches the people out when they move the files. A file at service/PricingService.java that declares package com.tutorsbot.model; compiles, but the compiler will not find it where you expect it, and the import in another class fails.
What are the layers, and why?
Look at the layout below.
src/
main/
java/
com/tutorsbot/shop/
Main.java
model/
Product.java
Order.java
service/
PricingService.java
InventoryService.java
io/
ConsoleReport.java
FileReport.javaThere are three packages, each with a clear job. The model package knows nothing about anything else. It holds Product and Order, and those classes know about themselves and about the data that they carry. The service package holds the rules and it depends on the model. The io package knows how to read and to write, and it depends on the model but not on the services. And Main sits at the top, it wires the pieces together, and it is the only class that imports from every package.
That dependency direction is the point. A model class never imports a service, so you can test the model without a database, without a console, or without anything else. The services can be tested without a console. And the io classes can be swapped, a console report today and a web endpoint tomorrow, without touching a line of the business logic.
What should a model class look like?
A record is a natural fit when the class is just the data. It is short, it is valid by construction, and the invariants are checked in one place.
package com.tutorsbot.shop.model;
public record Product(String sku, String name, double price, int stock) {
public Product {
if (sku == null || sku.isBlank()) {
throw new IllegalArgumentException("sku is required");
}
if (price < 0) {
throw new IllegalArgumentException("price cannot be negative");
}
}
public boolean inStock() {
return stock > 0;
}
public static void main(String[] args) {
Product product = new Product("KB-01", "Keyboard", 49.0, 12);
System.out.println("product : " + product);
System.out.println("in stock : " + product.inStock());
try {
new Product(" ", "Nameless", 10.0, 1);
} catch (IllegalArgumentException e) {
System.out.println("rejected : " + e.getMessage());
}
}
}The output is this.
product : Product[sku=KB-01, name=Keyboard, price=49.0, stock=12]
in stock : true
rejected : sku is requiredThere are two things to notice. The compact constructor rejects a blank sku and a negative price, so an invalid Product cannot exist. The check happens at the point of the creation rather than being repeated at every use. And the method inStock is the behaviour that belongs with the data, and not in a service that has to know how the products work.
What goes in a service?
The services hold the rules that operate on the model. They take the data in, they do something with it, and they give a result back.
package com.tutorsbot.shop.service;
import com.tutorsbot.shop.model.Product;
import java.util.List;
public class PricingService {
private final double taxRate;
public PricingService(double taxRate) {
this.taxRate = taxRate;
}
public double totalWithTax(List<Product> products) {
double net = products.stream().mapToDouble(Product::price).sum();
return round(net * (1 + taxRate));
}
public double priceOf(Product product) {
return round(product.price() * (1 + taxRate));
}
private double round(double value) {
return Math.round(value * 100) / 100.0;
}
}The output of that service is this.
net total : 68.5
with tax : 82.2
one item : 58.8That service takes a list of the products and it works out the total. Notice what it does not do. It does not print, it does not read a file, and it does not reach for a global. Every one of those would make it untestable, because a test would have to capture the output or to set up a file. The rounding is deliberate too. Rounding to the two decimals is the kind of the business rule that belongs in the service and not scattered through the code that happens to display the number. When the rounding changes, you change it in one place.
What should the entry point do?
The main method wires the things together and nothing else. Here it is next to the console reporter that it uses.
package com.tutorsbot.shop;
import com.tutorsbot.shop.io.ConsoleReport;
import com.tutorsbot.shop.model.Product;
import com.tutorsbot.shop.service.PricingService;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Product> catalogue = List.of(
new Product("KB-01", "Keyboard", 49.0, 12),
new Product("MS-02", "Mouse", 19.5, 0),
new Product("MN-03", "Monitor", 189.0, 4));
PricingService pricing = new PricingService(0.2);
ConsoleReport report = new ConsoleReport();
report.printCatalogue(catalogue);
report.printTotal(pricing.totalWithTax(catalogue));
catalogue.stream()
.filter(product -> !product.inStock())
.forEach(product -> report.printOutOfStock(product));
}
}The output is this.
KB-01 Keyboard 49.0
MS-02 Mouse 19.5
MN-03 Monitor 189.0
total with tax : 309.0
out of stock : MS-02Read it from the top to the bottom and you can see the whole program structure. Build the data, create the service, create the reporter, and then use them. There is no business rule here, and that is exactly right. The main method is the one place where it is acceptable to know about every class, because its job is to connect them. If your main method grows past about the thirty lines, then it is usually a sign that some logic belongs in a service.
How do you keep the layers decoupled?
| Layer | May depend on | Must not contain |
|---|---|---|
| model | Nothing but the standard library | Printing, files, services |
| service | model | Console output, hard-coded paths |
| io | model | Business rules |
| main | Everything | Logic worth testing |
There are two practical techniques that keep this honest. You pass the things that a class needs into its constructor rather than letting it create them, so that a test can supply a different implementation. And you keep the classes in the same package when they are closely related, because a package per class is its own kind of the noise.
How should you name the packages?
You start with a domain that will not change, such as your organisation or your project name, and then you add the layer, and then the feature. The name com.tutorsbot.shop.service.pricing is clearer than com.tutorsbot.utils.helpers, because it says what the code is and where it sits.
Avoid the generic names like util and common. They become the dumping grounds, because anything fits in a package that is called "util".
The habits to keep
- One public class per file, with the package matching the folder.
- Keep the model layer free of any dependency on the rest of the code.
- Pass the collaborators in through the constructor.
- Keep main short. It wires, and it does not calculate.
- Name the packages after the feature, and not after their technical role.
- Do not create a package per class. Group the related classes.
Try it yourself: build a four-class program for tracking the study sessions. You have a Session record with a topic, a duration and a date, a StudyService that totals the time per topic, a ConsoleReport that prints the totals, and a Main that wires them together. Then write a second version where the report is written to a file instead of the console, and confirm that neither the model nor the service changed by a single line.