Clean code series: 1. Naming, functions and control flow · 2. Error handling, boundaries and refactoring
Part 1 covered naming, functions, classes and control flow. This part goes where clean code breaks most often: error paths, the boundary with other people’s code, tests, and refactoring legacy code without changing behaviour. The last section is a refactor of a legacy checkout function behind a golden master test, and what it caught that eyes missed.
At a glance:
flowchart LR
SDK[Third-party SDK] --> AD[Adapter]
AD -->|"wrap checked exceptions"| SV["Service: unchecked exceptions"]
AU[ArchUnit] -.->|blocks type leaks| AD
T{What to test with?} -->|pure logic| O[Real object]
T -->|stateful dependency| FK[Fake]
T -->|interaction is behaviour| MK[Mock]
GM[Golden master] --> SS[Small steps]
SS --> CO[Separate refactor commits]
1. Error handling
Key idea: good error handling leaves the state consistent, writes messages you can diagnose from at 3 a.m., and catches only where it can do something.
Four rules
Write the try / catch / finally skeleton first. For code that can fail (I/O, network calls, parsing), write the error-handling frame before the logic, so you answer early: if this fails, what does the caller get? In modern Java, finally is almost always try-with-resources.
Treat a try block like a transaction. Either everything inside succeeds or the state is as it was. A catch block must leave the program in a consistent state.
Messages with context. The slide lists three parts: the type and severity of the failure; where it failed, as subject + verb + object; and why.
throw new PaymentException("Error"); // useless when reading logs at 3 a.m.
throw new PaymentException("Failed to capture payment " + paymentId
+ " for order " + orderId + ": gateway returned 402 (insufficient funds)", cause);
The second one tells you at once what broke, for which entity and why, and keeps the cause for the original stack trace. Keep sensitive data (card numbers, tokens) out of messages, because messages go straight into logs.
Centralised handling. Don’t try/catch to log and rethrow at every layer (one error logged five times). Catch where you can do something (retry, fall back, translate to a domain error), and let everything else bubble up to one shared handler. In Spring that is a @RestControllerAdvice returning ProblemDetail, covered in Spring Boot error handling; the basics are in exceptions in Java.
Checked or unchecked
A checked exception is one the compiler forces you to catch or declare with throws; an unchecked one (a subclass of RuntimeException) isn’t. Checked ones remind the caller, but a low-level throws ripples up every signature and leaks details like SQLException.
The slide’s checked/unchecked table and using checked exceptions in lambdas
The slide’s summary:
| Checked | Unchecked | |
|---|---|---|
| Definition | Checked by the compiler; failures outside the program’s control; methods must catch or declare throws |
Not checked at compile time; usually logic errors; no throws needed |
| Pros | Reminds callers to handle them | Preserves encapsulation, low cost |
| Cons | Violates Open-Closed (a new throws at a low layer ripples up every signature), breaks encapsulation (leaks details like SQLException) |
Easy to forget to handle |
| Use for | Critical libraries | General applications |
Checked exceptions and lambdas don’t mix, because Function.apply declares no throws. The clean fix is to wrap in one place:
@FunctionalInterface
interface IOFunction<T, R> { R apply(T t) throws IOException; }
static <T, R> Function<T, R> uncheckedIO(IOFunction<T, R> f) {
return t -> {
try { return f.apply(t); }
catch (IOException e) { throw new UncheckedIOException("I/O failed for " + t, e); }
};
}
List<String> contents = paths.stream().map(uncheckedIO(Files::readString)).toList();
2. Comments and formatting
Key idea: comments are for saying why; formatting is the machine’s job.
- Do comment: complex algorithms, the reason behind a non-obvious decision (“
LinkedHashMapbecause display order must follow insertion order”), and the contract of public interfaces: which parameters may be null, what is thrown, whether it is idempotent. - Don’t comment to explain what code does; rename or extract instead.
Formatting: Spotless with google-java-format in the build (spotlessCheck fails CI on a formatting violation), Checkstyle for naming conventions. Configure it once and stop arguing about braces in reviews.
3. Tests
Key idea: a test holds only the details that drive the result, and checks behaviour rather than restating the implementation.
Include only relevant details. A test for “GOLD customers get 10% off above 1 million” doesn’t need an address or a date of birth. Use a test data builder with valid defaults: anOrder().tier(GOLD).subtotal("1200000").build().
Don’t overuse mocks. Mocking every collaborator and verify-ing every call just restates the implementation: reordering internal calls turns the test red even though behaviour didn’t change.
4. Boundaries: where your code meets other people’s code
Key idea: wrap third-party libraries and SDKs behind an adapter that speaks your types, so changes on their side touch one place.
A boundary is wherever you call a library, a vendor SDK or another team’s API: an unpredictable area, because they change versions and semantics and throw odd exceptions. The slide’s advice:
- Don’t pass third-party objects around your system, and don’t accept or return them in your public APIs.
- Buffer the boundary with an adapter (the slide’s picture is the hexagonal, or ports and adapters, architecture: the core only talks through its own interfaces).
- Write learning tests.
Example: an SMS SDK from a vendor called “Acme” with its own types and checked exceptions carrying numeric codes.
// Port: our language, our types
interface SmsSender { SmsResult send(PhoneNumber to, String text); }
sealed interface SmsResult {
record Sent(String providerMessageId) implements SmsResult {}
record Rejected(String reason) implements SmsResult {}
}
// Adapter: the only place that knows Acme exists
final class AcmeSmsSender implements SmsSender {
private final AcmeSmsClient client;
AcmeSmsSender(AcmeSmsClient client) { this.client = client; }
public SmsResult send(PhoneNumber to, String text) {
try {
AcmeSmsResponse response = client.send(to.e164(), text, Map.of("priority", "high"));
return new SmsResult.Sent(response.messageId);
} catch (AcmeSmsException e) {
if (e.vendorCode / 1000 == 4) { // 4xxx: our fault, retrying won't help
return new SmsResult.Rejected("provider rejected " + to.e164() + ": " + e.getMessage());
}
throw new SmsUnavailableException(
"Failed to send SMS to " + to.e164() + " via Acme (code " + e.vendorCode + ")", e);
}
}
}
The payoff: switching vendors means a new adapter without touching the service; service tests use a few-line fake SmsSender; the “4xxx means our fault” convention lives in one place. Run on JDK 21 (with a simulated SDK): a successful send returns Sent, and code 5003 becomes SmsUnavailableException with the cause preserved.
In DDD, when the other side is a whole different model (an ERP, a core banking system), this layer grows and is called an anti-corruption layer (a layer that stops a foreign model from corrupting yours). The adapter pattern itself is in Adapter and Factory.
A learning test checks your assumptions about the library: “the client throws 4001 for a non-E.164 number”, “does it retry by itself”, “what is the default timeout”. Rerun them when upgrading the SDK and you know at once whether semantics changed.
5. Refactoring
Key idea: refactoring changes internal structure without changing observable behaviour. Tests written first and small steps are what make it safe.
The safe workflow:
- Characterization tests first (tests that record what the code currently does, including behaviour that looks like a bug).
- Small steps, run the tests after each; if red, revert the step instead of debugging.
- Use the IDE’s automated refactorings (Extract Method, Rename, Change Signature): more reliable than hand edits, including at distant call sites.
- Keep refactoring commits separate from behaviour changes, so the reviewer asks one question only: did behaviour change?
Fowler’s four groups of techniques and the slide’s “3 classes, 10 files” note
The slide lists four groups of techniques from Martin Fowler’s catalogue:
| Group | Example techniques | Concrete example |
|---|---|---|
| Composing methods | Extract Method, Replace Temp with Query, Inline | Extract domesticBaseFee(cart) from the fee function |
| Moving features between objects | Move Method, Extract Class, Hide Delegate | Move the line-amount calculation into OrderLine.amount() |
| Organizing data | Replace Magic Number with Constant, Replace Primitive with Object, Replace Type Code with Class | "GOLD" becomes enum Tier, double money becomes BigDecimal |
| Dealing with generalization | Replace Conditional with Polymorphism, Extract Interface, Replace Inheritance with Delegation | An if (v.equals("SALE50")) chain becomes sealed interface Voucher |
The slide also says “best practices: 3 in-depth classes, 10 files, unit tests” without explanation. I read it as a scope limit for one refactoring: don’t go more than about three class levels deep or touch more than about ten files in one change, and have unit tests first. That fits the four-step workflow above.
6. Case study: refactoring a checkout function
Key idea: a 20,000-case golden master let me refactor a legacy checkout function with 0 differences, and it caught a rounding change that shifted money and that eyes missed.
This is the course homework: I wrote a checkout function with every legacy “speciality” and refactored it following the workflow in section 5.
The starting point
A method process(Map<String, Object> req) takes a map-shaped request and returns the string "OK:<orderId>:<total>" or "ERROR:<code>".
Smells: one-letter names, magic numbers, double for money, catch (Exception e) swallowing errors, five levels of nesting, parsing/pricing/saving/logging mixed in one function, static state (counter, DB), and a result string callers have to parse again.
The homework brief, code size and an excerpt of the legacy process() method
Brief: refactor at least 300 lines of your own real code (several classes, business logic, the fewer comments the better, no getters/setters, nothing company-sensitive). I can’t put work code on a blog, so I wrote sample code. About 365 lines in total: the old version is 95 lines, the new one about 205 lines across 6 files, and the golden master about 65 lines.
public String process(Map<String, Object> req) {
String cid = (String) req.get("cid");
String items = (String) req.get("items"); // "sku:qty:price;sku:qty:price"
String v = (String) req.get("voucher");
String t = (String) req.get("tier");
String pm = (String) req.get("pm");
double sub = 0;
int cnt = 0;
if (cid != null && !cid.isEmpty()) {
if (items != null) {
String[] arr = items.split(";");
for (int i = 0; i < arr.length; i++) {
try {
String[] p = arr[i].split(":");
int q = Integer.parseInt(p[1]);
double pr = Double.parseDouble(p[2]);
if (q > 0) { sub = sub + q * pr; cnt = cnt + q; }
} catch (Exception e) {
// ignore bad item
}
}
if (cnt == 0) return "ERROR:EMPTY";
double d = 0;
if (t != null) {
if (t.equals("GOLD")) {
if (sub > 1000000) { d = sub * 0.1; } else { d = sub * 0.05; }
} else if (t.equals("SILVER")) {
if (sub > 1000000) { d = sub * 0.05; }
}
}
// ... vouchers SALE50 / PCT20 / FREESHIP, 30000 shipping, 5000000 COD limit,
// payment method check, static counter++, DB.add(...), System.out.println(...)
Step 1: a golden master before touching anything
There were no tests, so I used a golden master: generate many inputs, run them through the old code, record the outputs; every later version must produce exactly the same. A fixed seed and deliberately bad values mean the 20,000 cases exercise every branch.
List<Map<String, Object>> cases = cases(7, 20_000); // fixed seed: same inputs every run
List<String> before = cases.stream().map(new legacy.OrderProcessor()::process).toList();
List<String> savedRows = new ArrayList<>();
AtomicInteger ids = new AtomicInteger(1000);
CheckoutService svc = new CheckoutService(
(id, cid, total, pm) -> savedRows.add(id + "," + cid + "," + total + "," + pm),
() -> "O" + ids.incrementAndGet());
List<String> after = cases.stream().map(svc::process).toList();
// compare before/after element by element, and savedRows with legacy.OrderProcessor.DB
The input generator and how the 20,000 cases split
The generator mixes in: null or empty customer ids, item lines with missing fields, negative quantities, non-numeric prices, 1e5, a fractional 7777.5, unknown vouchers and tiers, unknown payment methods, orders big enough to hit the COD limit.
| Outcome | Cases |
|---|---|
| Success | 8,495 |
| Missing customer | 5,057 |
| Empty order | 3,948 |
| Bad payment method | 2,179 |
| Over the COD limit | 321 |
Steps 2 to 5: refactor step by step
Five steps, each one technique from section 5: pull parsing out to the boundary, meaningful types, polymorphism instead of if, a pure pricing core, typed results. Final result: 20,000 cases, 0 differences, and the 8,495 “saved” rows are identical (run on JDK 21).
The five steps in detail and the service code afterwards
In a real project each step below is its own commit with a green golden master (for this post I ran the golden master on the final version and on the experiments in the next section):
- Pull parsing out to the boundary:
LegacyRequestParserturns the untyped map into a typedOrderRequest; everything messy (casts, string splitting, the"COD"default) lives there. - Organizing data:
record OrderLine(sku, quantity, unitPrice),enum Tier,enum PaymentMethod,BigDecimalfor money, named constants for every threshold. - Replace conditional with polymorphism:
sealed interface VoucherwithFixedAmount,Percentage,FreeShippingand aVoucher.fromCode(code)factory. - Extract a pure core:
PriceCalculator.price(request)returns aPriceBreakdown(subtotal, two discounts, shipping), with no I/O and no state. - Typed results, injected dependencies:
sealed interface CheckoutResult(Placed,Rejectedwith anenum RejectReason); the repository and id generator come in through the constructor. The oldprocess(map)is now a one-line adapter for existing callers.
The service layer afterwards:
CheckoutResult checkout(Map<String, Object> rawRequest) {
return switch (parser.parse(rawRequest)) {
case Parsed.Invalid invalid -> new CheckoutResult.Rejected(invalid.reason());
case Parsed.UnknownPaymentMethod unknown -> new CheckoutResult.Rejected(UNSUPPORTED_PAYMENT_METHOD);
case Parsed.Valid valid -> place(valid.request());
};
}
private CheckoutResult place(OrderRequest request) {
BigDecimal total = calculator.price(request).total();
if (request.paymentMethod() == PaymentMethod.COD && total.compareTo(COD_LIMIT) > 0) {
return new CheckoutResult.Rejected(RejectReason.COD_LIMIT_EXCEEDED);
}
long roundedTotal = total.setScale(0, RoundingMode.HALF_UP).longValueExact();
String orderId = orderIds.get();
repository.save(orderId, request.customerId(), roundedTotal, request.paymentMethod());
return new CheckoutResult.Placed(orderId, roundedTotal);
}
What the golden master caught
I tried a harmless-looking “improvement”: round the tier discount as soon as it’s computed, because “money should be an integer”. The golden master went red at once: 338 of 20,000 cases differed by one dong.
A green golden master doesn’t mean identical behaviour for every input either. A probe (a separate set of test inputs) with “weird” values found four differences, such as a NaN price creating a 0-dong order in the old code.
The weird-value probe table and the decision for each difference
| Item line | Old code | New code |
|---|---|---|
A:1:NaN |
OK:...:0 (an order for 0 dong!) |
ERROR:EMPTY |
A:1:19900d |
OK:...:49900 (Double.parseDouble accepts a d suffix) |
ERROR:EMPTY |
A:1: 19900 |
OK:...:49900 (leading whitespace ignored) |
ERROR:EMPTY |
A:1:Infinity |
ERROR:COD_LIMIT |
ERROR:EMPTY |
A:1:-50000 |
OK:...:-20000 |
OK:...:-20000 |
Decisions:
- A
NaNprice producing a 0-dong order is a bug and the new behaviour is better: keep it, called out in the PR as a deliberate behaviour change with its own test. - Negative prices create negative totals in both versions: a real bug, but fix it in a commit after the refactor, so reviewers can see which is refactoring and which is a fix.
- The old code’s
System.outlines are not in the golden master; if any system reads that log, it needs pinning down too.
7. Code review
Key idea: for a refactoring PR, state “this commit doesn’t change behaviour, and the golden master is the evidence”, so the reviewer can focus on design.
The rest of the slides (checklist, process, TODO/NIT/OPTIONAL/FYI labels, PR size, disagreements) is in effective code review and resolving disagreements and sample reviews.
8. Recap
Key idea: clean code is not the goal but a way to lower the cost of change; it is balanced against delivery speed, how the team collaborates and performance.
In short: four “-ables”; abstraction reduces complexity; inconsistency breeds unknown unknowns; read and practise. The old checkout function ran for years; the reason to refactor it was that it was about to change a lot, not that it was ugly.
Exercises
Exercise 1: Add a voucher type
Task: add a BIG100 voucher worth 100,000 off orders of at least 1,000,000 (after the tier discount). Then answer: could a “buy 2 get 1 free” voucher be added the same way?
Solution to exercise 1
One line in the factory, without touching PriceCalculator or the service:
case "BIG100" -> Optional.of(new FixedAmount(new BigDecimal("100000"), new BigDecimal("1000000")));
The golden master still shows 0 differences, and two dedicated tests ran: a 1,200,000 order comes to 1,100,000 (free shipping), a 900,000 order gets no discount.
“Buy 2 get 1” can not be added that way: discountOn(BigDecimal) only sees a single number, while this voucher needs the individual lines, so the signature must become discountOn(List<OrderLine>, BigDecimal). Abstractions are designed for the variants you know about; when a new variant breaks an assumption, change the abstraction deliberately instead of bolting on a flag.
Remember
- Can you explain why a
catchmust leave consistent state, and what a good error message contains? - Do you know when to use checked vs unchecked exceptions, and where to wrap checked ones?
- Can you pick a real object, a fake or a mock for a dependency, and say why?
- Can you describe wrapping an SDK behind an adapter and stopping vendor types from leaking?
- Can you walk through the golden master workflow and say why it doesn’t cover every input?
Interview questions
Junior
Why not just catch (Exception e) {} and move on?
Because the error vanishes without a trace and the program carries on with bad data.
For example a NaN price becomes a 0-dong order, with no logs to investigate. Catch only what you can handle, actually handle it, or let it bubble up to the shared handler.
What makes a good error message?
What failed, for which entity, why, and the original exception kept as the cause.
The type of failure; the order id or file name; the return code or bad value. No sensitive data such as card numbers or tokens.
When should you write a comment?
When you need to explain why, not what the code does.
That means a non-obvious decision, a complex algorithm, and the contract of public interfaces in Javadoc. To explain what code does, rename or extract a method instead.
Mid
Checked or unchecked exceptions for business errors in a Spring service?
Usually unchecked, carrying structured data and handled centrally with @RestControllerAdvice.
Checked exceptions spread through every signature, don’t work in lambdas, and Spring itself goes unchecked (DataAccessException). Checked exceptions from libraries get wrapped at the boundary with their cause.
What’s wrong with heavy mocking in unit tests?
Tests get coupled to the implementation: internal refactoring turns them red even though behaviour is unchanged, so people stop refactoring.
Use real value objects and pure logic, fakes for stateful dependencies, and keep mocks for interactions that are the behaviour under test. Needing many mocks usually means the class does too much.
What is a learning test?
A test that checks your understanding of a third-party library, not your own code.
For example: what it throws on bad input, whether it retries, its default timeout. Rerun them on upgrades to catch semantic changes before production does.
Senior
How do you refactor a legacy function that has no tests?
Golden master first, then small steps with the IDE’s refactoring tools, comparing after each one.
Generate many inputs including bad ones and record the old code’s output; keep refactoring commits apart from behaviour changes. Add probes wherever a type or library is swapped, because a golden master only protects what the generator produces.
How do you wrap a vendor SDK, and why?
A port in your own types and an adapter that is the only place importing the SDK, so switching vendors only touches the adapter.
Define an SmsSender interface and an SmsResult; the adapter translates their exceptions and error codes into your semantics and keeps the cause. Switching vendors or upgrading a major version only touches the adapter, and service tests use a fake. An ArchUnit rule in CI stops the leak.
A refactor shifted the total by one dong on 338 of 20,000 orders. What do you do?
Treat it as a behaviour change, not a detail: revert that step.
When and how to round is a business rule, so ask the business owner or accounting and write it down as a tested specification. If the decision is to change it, do it in its own commit, with communication and a reconciliation plan for existing orders.
When do you not refactor?
When code is ugly but stable and rarely changed.
Also not when there’s no way to verify behaviour and writing the tests costs more than the benefit, or right before a risky release. Clean code is a way to lower the cost of change; where nothing changes, the benefit is close to zero.
Useful phrases for interviews
- “Before touching legacy code, I pin its current behaviour down with characterization tests.”
- “This commit is behaviour-preserving, and the golden master is the evidence.”
- “Swallowing that exception turns a parsing error into silently wrong data.”
- “I’d keep the vendor’s types behind an adapter so they never cross the boundary.”
- “The rounding mode is a business rule, not an implementation detail.”
- “I prefer a fake over a mock here, so the test survives refactoring.”
- “Let’s split this into a refactoring PR and a behaviour-change PR.”
- “Clean code isn’t the goal; we refactor where the code is about to change a lot.”
Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.