SteelReed

Search

Search posts, questions…

3. Advanced Java

Clean code: error handling, boundaries and behaviour-preserving refactoring

Why a "just tidying" refactor still shifts money: hidden behaviour lives in error paths, SDK boundaries, type changes and rounding. Pin behaviour with a golden master first, wrap SDKs behind adapters, and review AI-written characterization tests and refactors.

18 Nov 20267 min readSenior

–

1. The problem

An AI refactors a 95-line checkout function, the PR says "refactor only", and the old unit tests stay green. A 20,000-order golden master goes red: 338 orders are off by one dong because the discount is rounded too early. No old test checked rounding.

2. Key idea

Unit tests check what the author thought of. Hidden behavior lives where nobody thought. Rule: lock behavior first, change structure second, and each commit changes only one of the two. At a boundary, translate foreign things into your own types exactly once.

Where behavior hides Example Why old tests miss it
Error paths catch (Exception e) silently drops a broken line item tests only feed valid input
Boundaries the SDK returns 4xxx for client-side errors the mock returns what you told it to
Type changes Double.parseDouble accepts NaN, new BigDecimal(String) doesn't nobody generates NaN input
Rounding rounding each step versus once at the end off by one dong looks right

2.1 Which technique?

Technique Use when Don't use when
Golden master untested legacy code with comparable output output contains times or random ids you can't pin
Edge-value probes the refactor changes types or parsing libraries only renaming or IDE function extraction
Adapter around an SDK SDKs or other teams' APIs that change versions, throw odd errors stable standard libraries like java.time

3. In Java

JAVA
@Test
void refactorKeepsBehaviour() {
    List<Map<String, Object>> cases = cases(7, 20_000);   // fixed seed, includes bad input
    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();
    assertEquals(before, after);   // every element, including "ERROR:<code>"
    // and compare savedRows with legacy.OrderProcessor.DB: side effects are behavior too
}

Other languages: Go keeps golden files in testdata/; Node.js has Jest snapshot tests; C# has Verify.

Error handling and boundaries
  • Unchecked domain errors (InsufficientStockException extends RuntimeException): Spring rolls back on unchecked exceptions by default, and callers don't need throws everywhere. Keep checked exceptions for library APIs where callers can recover on the spot.
  • Never catch (Exception e) and swallow it. When wrapping, keep the cause; messages never include card numbers or tokens.
  • A catch must leave state consistent: roll back, or change nothing until success is certain.
  • Adapter: SDK types and exceptions live in one package; nothing else imports the vendor package (check with grep or ArchUnit).
  • Learning tests: a few tests calling the SDK directly to record the behavior you rely on (which error code means what). Rerun them on every upgrade.

4. Working with AI

Hand to AI: listing branches and edge values, writing a seeded input generator and characterization tests, proposing small refactor steps, writing adapters and learning tests.

Check yourself in AI-written code:

  • Test expectations come from the old code's output, not the AI's reasoning or the new code.
  • The input set has a fixed seed and includes error cases; print case counts per result type.
  • Tests compare side effects (saved rows, sent events), not just return values.
  • No catch (Exception e) swallowing errors; no vendor imports outside the adapter.
  • The PR description lists every behavior difference; behavior changes sit in their own commit.

5. Exercises

Exercise 1: Review an AI-written golden master

The AI's PR says: "Golden master, 20,000 cases, green, the refactor is safe". Find what the test doesn't protect, show how to prove it, fix it.

JAVA
@Test
void goldenMaster() {
    for (Map<String, Object> c : cases(7, 20_000)) {
        String before = new legacy.OrderProcessor().process(c);
        String after = svc.process(c);
        // only compare successful orders to keep it short, error cases don't affect revenue
        if (before.startsWith("OK")) assertEquals(before, after);
    }
}
Solution 1

The test only compares the 8,495 successful cases; the 11,505 error cases (57%) are unprotected. It also protects only one direction: the new code wrongly rejecting a valid order fails, but wrongly accepting an order that should be rejected stays green.

Prove it with a mutant: make the new parser treat unknown payment methods as COD. The old code returns ERROR:..., the if skips it, the test stays green, and 2,179 bad orders now go through.

Fix: compare every element, compare saved data too, print case counts per result type. "Error cases don't affect revenue" is wrong: accepting an order over the COD limit or with a NaN price is lost money.

Exercise 2: Read an incident after an SDK upgrade

After an SMS SDK upgrade, OTP delivery drops from 99.2% to 71%, with no 5xx alerts. The log repeats SmsResult.Rejected: rate limited (code 4290). The adapter treats vendorCode / 1000 == 4 as Rejected (client-side, no retry). Diagnose it, say what to do in 15 minutes, fix the root cause.

Solution 2
  • Diagnosis: the new version uses 4290 for rate limiting, a temporary error. The adapter files every 4xxx under "retry is pointless" and returns Rejected. Rejected is a normal result, not an exception, so no alert fires.
  • 15 minutes: roll back to the old SDK, or hotfix: 4290 throws SmsUnavailableException so the layer above retries with backoff. Add an alert on the Rejected rate.
  • Root fix: replace the / 1000 rule with an explicit error-code table, defaulting unknown codes to temporary with a warning log. Write learning tests for error-code semantics and rerun them on every SDK upgrade.

Summary

  • A refactor keeps observable behavior, including error paths and rounding.
  • Lock behavior with a golden master first; expectations come from the old code.
  • Compare side effects too; type changes need dedicated probes.
  • SDK types and error codes live only in the adapter, with learning tests.
  • Behavior changes go in their own commit and are listed in the PR.

Further reading: Readable code for people and AI.

Practice interview questions on this topic

All OOP & Design questions →

Loading comments…
Next on the roadmapDates and times in the backend: epoch, UTC, time zones, ISO 8601 and java.time