Code Quality: Clean Code in Java. Practical Tasks
Rename Proc.calc() to OrderCalculator.total(), replace x[1] > 3 with a named constant, and the program prints exactly the same number as before — that is the point of refactoring. These clean code exercises in Java give you working but messy code and ask you to make it readable without changing what it does.
The tasks practice the module «Code Quality»: meaningful names, small methods without flag arguments, command-query separation, error handling without null, SOLID and the most common code smells. Each task starts from a piece of code that compiles and runs; finish each one with a check or a unit test that proves the behavior stayed the same.
What to Review Before You Start
Every task relies on one or two lessons of the module. If a rule in a task looks unfamiliar, open the matching section first — each one has a bad and a good version of similar code.
| Lesson | What you need from it in the tasks |
|---|---|
| Meaningful Names | Names that reveal intent, constants instead of literals |
| Clean Methods | Extracting methods, flag arguments, command-query separation |
| Clean Error Handling and Unit Tests | Exceptions with context, no null results, given-when-then tests |
| SOLID Principles | Dependency inversion, open-closed principle |
| Code Smells | Repeated switch, encapsulated conditions, Optional and toList() |
Rename an Order Calculator So It Explains Itself
The class below calculates the total of an order: each line has a price in cents and a quantity, and lines with more than three items get a 10% discount. Nothing in the code says so.
import java.util.ArrayList;
import java.util.List;
public class Proc {
private List<int[]> l = new ArrayList<>();
public void add(int a, int b) {
l.add(new int[]{a, b});
}
public int calc() {
int t = 0;
for (int[] x : l) {
if (x[1] > 3) {
t += x[0] * x[1] * 90 / 100;
} else {
t += x[0] * x[1];
}
}
return t;
}
} - Rename the class, the field, the methods, the parameters and the local variables so that each name tells what it holds or does.
- Replace
int[]with a recordOrderLine(int priceCents, int quantity), so thatx[0]andx[1]disappear. - Replace the literals
3,90and100with named constants, for exampleBULK_QUANTITYandBULK_DISCOUNT_PERCENT. - Make sure the behavior has not changed: an order with the lines (100 cents × 2) and (250 cents × 4) must still total
1100.
Before you rename
Write the check for 1100 first, run it against the original class, and only then start renaming with the IDE (Shift+F6 in IntelliJ IDEA). Keep the integer arithmetic exactly as it is: 250 * 4 * 90 / 100 is 900, and switching to double would change rounding for other prices.
Split a Report Method with a Flag Argument
A sales report is printed in two forms, short and detailed, and a boolean parameter chooses between them:
import java.util.List;
public class SalesReport {
record Sale(String product, int quantity, double price) {}
public void print(List<Sale> sales, boolean detailed) {
System.out.println("=== Sales report ===");
double total = 0;
for (Sale sale : sales) {
total += sale.quantity() * sale.price();
if (detailed) {
System.out.printf("%-10s %3d x %8.2f%n", sale.product(), sale.quantity(), sale.price());
}
}
System.out.printf("Total: %.2f%n", total);
}
} - Replace
print(List<Sale>, boolean)with two public methods whose names say what they print, for exampleprintSummary(sales)andprintDetailed(sales). - Do not duplicate code between them: extract the header, the total calculation and the line formatting into private methods.
- Calculate the total in a separate method that returns a value and prints nothing, so it can be reused and tested.
- Show both reports for three sales of your choice in
mainand check that the totals are identical.
Hint
Look at the call sites first: report.print(sales, true) says nothing without the declaration, while report.printDetailed(sales) needs no explanation. If a third format appears later, an enum ReportFormat is a better parameter than a second boolean.
Extract Methods from a Reminder Loop and Make It Testable
This method sends a reminder to customers whose subscription ends within seven days. It mixes a business rule, text formatting and sending, and it reads the current date directly, so it cannot be tested for a fixed day.
public void sendReminders(List<Subscription> subscriptions) {
for (Subscription s : subscriptions) {
if (s.isActive() && s.getEndDate().minusDays(7).isBefore(LocalDate.now()) && !s.isReminderSent()) {
String text = "Dear " + s.getCustomerName() + ",\nyour subscription ends on "
+ s.getEndDate().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")) + ".";
mailer.send(s.getEmail(), "Your subscription is ending", text);
s.markReminderSent();
}
}
} - Extract the condition into a method with a name that states the rule, for example
needsReminder(Subscription). - Extract the text into
buildReminderText(Subscription)and the sending intosendReminder(Subscription), so thatsendRemindersreads as one level of abstraction. - Replace
LocalDate.now()with ajava.time.Clockpassed through the constructor, and the literal7and the date pattern with named constants. - Write unit tests with
Clock.fixed(...)and a fake mailer: a subscription ending in 3 days gets a reminder, one ending in 30 days does not, and a subscription whose reminder was already sent gets nothing. - Check the boundary: does a subscription that ends in exactly 7 days get a reminder? Decide what the rule should be and make the test say it.
The boundary hides in isBefore
endDate.minusDays(7).isBefore(today) is false when the end date is exactly seven days away, so that customer gets the reminder a day later than you might expect. A named method such as !today.isBefore(endDate.minusDays(REMINDER_DAYS)) or a ChronoUnit.DAYS.between(today, endDate) <= REMINDER_DAYS check makes the rule explicit.
Separate the Command from the Query in an Inventory
The method reserve answers a question and changes the stock at the same time. At the call site if (inventory.reserve("SKU-1", 2)) it is not clear whether false means «not enough stock», «unknown product» or «already reserved».
import java.util.HashMap;
import java.util.Map;
public class Inventory {
private final Map<String, Integer> stock = new HashMap<>();
public void addStock(String sku, int quantity) {
stock.merge(sku, quantity, Integer::sum);
}
public boolean reserve(String sku, int quantity) {
Integer available = stock.get(sku);
if (available == null || available < quantity) {
return false;
}
stock.put(sku, available - quantity);
return true;
}
} - Add a query
boolean canReserve(String sku, int quantity)that changes nothing, and a queryint available(String sku)that returns0for an unknown product. - Turn
reserveinto a command that returnsvoidand throws an exception with context when the reservation is impossible, for example"Cannot reserve 5 of SKU-1: only 2 available". - Reject a quantity that is zero or negative with
IllegalArgumentException. - Write tests for a successful reservation, for not enough stock and for an unknown product. Each test should check one behavior.
Where CQS meets concurrency
The pair if (canReserve(...)) reserve(...) is not atomic: in a multithreaded service another thread can take the stock between the two calls. That is why reserve must still check the stock itself and fail with an exception, and why the JDK breaks CQS on purpose in methods like ConcurrentMap.putIfAbsent().
Replace StringBuilder Plumbing with a Small HtmlTag Class
The method below builds an <hr> tag by hand. HTML syntax (quotes, angle brackets) is mixed with the business rule «the size is one more than the configured value»:
public String render() {
StringBuilder html = new StringBuilder("<hr");
if (size > 0) {
html.append(" size=\"")
.append(size + 1)
.append("\"");
}
html.append(">");
return html.toString();
} - Create a class
HtmlTagwith a constructor that takes the tag name, a methodattribute(String name, String value)that returnsthis, and a methodtoHtml(). - Rewrite
render()so that it contains only the rule about the size and no HTML syntax. - Make
HtmlTagescape attribute values: a value containing"or&must not break the markup. - Check the results:
size = 2produces<hr size="3">,size = 0produces<hr>.
Hint
Keep the attributes in a LinkedHashMap, not a HashMap, so they are printed in the order they were added and the output is repeatable in tests. For escaping, replace & first and then ", < and >; otherwise the ampersands of already escaped characters get escaped twice.
Replace Repeated switch Statements with an Enum
A traffic light controller stores the color as an int and repeats the same switch in two methods. Adding a new state means finding and changing every switch.
public class TrafficLightController {
public static final int RED = 0;
public static final int GREEN = 1;
public static final int YELLOW = 2;
public int next(int color) {
switch (color) {
case RED: return GREEN;
case GREEN: return YELLOW;
case YELLOW: return RED;
default: throw new IllegalArgumentException("Unknown color " + color);
}
}
public int durationSeconds(int color) {
switch (color) {
case RED: return 30;
case GREEN: return 25;
case YELLOW: return 5;
default: throw new IllegalArgumentException("Unknown color " + color);
}
}
} - Replace the
intconstants with anenum TrafficLight, so that an invalid value such as7can no longer be passed. - Move the duration into the enum as a field set through the constructor, and the transition into a method
next(). - Remove both
switchstatements and thedefaultbranches that existed only for invalid numbers. - Add a new state
FLASHING_YELLOW(duration 0, next state is itself) and note how many places you had to change compared with the original class. - Print the cycle starting from
REDfor six steps together with the durations.
Two ways to write next()
You can declare abstract TrafficLight next() and implement it in each constant body, or keep one method with a switch expression over this. The switch expression over an enum needs no default: if a constant is missing, javac reports the switch expression does not cover all possible input values, which is exactly the safety net the int version did not have.
Apply Dependency Inversion to an Order Service
The service below creates its collaborators itself. It cannot be tested without a mail server, and the confirmation time changes on every run.
public class OrderService {
private final SmtpMailer mailer = new SmtpMailer("smtp.example.com", 25);
private final List<Order> orders = new ArrayList<>();
public void placeOrder(Order order) {
orders.add(order);
String text = "Order " + order.id() + " confirmed at " + LocalDateTime.now();
mailer.sendMail(order.customerEmail(), "Order confirmation", text);
}
} - Introduce an interface
Notifierwith one method, for examplevoid notify(String recipient, String subject, String text), and an adapterSmtpNotifierthat delegates toSmtpMailer. - Introduce an interface
OrderRepositorywith an in-memory implementation instead of the list field. - Pass
Notifier,OrderRepositoryand ajava.time.ClockintoOrderServicethrough the constructor;OrderServicemust not contain the wordnewfor any collaborator. - Write a JUnit test with a fake notifier that records messages and a fixed clock, and check the exact confirmation text.
- Assemble the real objects in
main(the composition root) and explain in a comment why only this place knows aboutSmtpMailer.
A fake is enough
You do not need a mocking library here: a fake can be a small class or even a lambda, because Notifier has one method. Store the received messages in a list and assert on it. With Clock.fixed(Instant.parse("2026-01-15T10:00:00Z"), ZoneOffset.UTC) and LocalDateTime.now(clock) the expected text is the same on every machine.
Remove null from a Customer Repository
Every method of this repository can return null, and every caller has to remember it:
public class CustomerRepository {
private final Map<String, Customer> byEmail = new HashMap<>();
public Customer findByEmail(String email) {
return byEmail.get(email); // null if not found
}
public List<Customer> findByCity(String city) {
List<Customer> result = new ArrayList<>();
for (Customer customer : byEmail.values()) {
if (customer.city().equals(city)) {
result.add(customer);
}
}
return result.isEmpty() ? null : result; // null instead of an empty list
}
} - Change
findByEmailto returnOptional<Customer>. - Change
findByCityto return an empty list when nothing is found; rewrite it with a stream andtoList(). - Reject
nullarguments withObjects.requireNonNulland a parameter name in the message. - Write a caller that greets a customer by email and throws
CustomerNotFoundExceptionwith the email in the message when there is no such customer. Do not useisPresent()together withget(). - Write a caller that prints the number of customers in a city; it must work without any
nullcheck for a city with no customers.
Watch the unmodifiable result
toList() returns an unmodifiable list. If an existing caller adds elements to the result of findByCity, it now fails with UnsupportedOperationException; such a caller should create its own copy with new ArrayList<>(...) instead of modifying what the repository returned.
Where Refactorings Go Wrong
Most broken solutions change the behavior by accident while «only cleaning up». The table lists what happens most often in these tasks and how to catch it before you call the task done.
| Mistake | What happens | How to avoid it |
|---|---|---|
| Refactoring without a check | A changed result goes unnoticed: int arithmetic replaced with double changes rounding | Write the test or the expected output first and run it before and after every step |
| Extracting a method that still uses fields as hidden inputs | The new method depends on the order of calls (hidden temporal coupling) | Pass the data as parameters and return the result |
Replacing collect(Collectors.toList()) with toList() blindly | A caller that adds to the list fails with UnsupportedOperationException | Check the callers, or copy the result where it is modified |
| A new interface for every class | More files, no gain: nothing is ever substituted | Introduce an interface where a test double or a second implementation is needed |
| Renaming by search-and-replace | Unrelated identifiers and strings change too | Use the IDE rename refactoring, which works on references, not text |
Frequently Asked Questions
Do I need JUnit for these exercises?
It is the most convenient way, and the tasks about the reminder loop and the order service ask for unit tests. For the simpler tasks, a main method that prints the result before and after the refactoring and compares the two values is enough.
Is there one correct solution for a refactoring task?
No. Names and the exact split into methods can differ. A solution is good when the behavior is unchanged, every method does one thing, names need no comments and the tests describe the rules. Compare your result with the checklist in Where Refactorings Go Wrong.
Should I fix the bugs I notice while refactoring?
Not in the same step. First make the code clean with the behavior unchanged and the tests green, then fix the bug in a separate step with a test that fails before the fix. Mixing both makes it impossible to tell which change broke something.
Can I use Lombok or a mocking library in the solutions?
You can, but the tasks are designed so that plain Java is enough: records replace most Lombok use, and a fake implementation of a one-method interface is simpler than a mock. Solving without libraries makes the clean code rules more visible.
Comments