SteelReed

Search

Search posts, questions…

3. Advanced Java

Code that humans and AI can read: naming, functions and control flow

Why readability sets the cost of change when your code's readers include both teammates and AI agents: Ousterhout's view of complexity, naming after questions, single-purpose functions, flat control flow, and how to review refactors written by AI.

18 Nov 20267 min readMid

–

1. The problem

The free-shipping threshold 500_000 is hard-coded in a controller, the pricing service and an email template. You ask an AI to change it to 300,000; it edits the two files it has open and reports done. Two weeks later customers complain the email still shows the old threshold.

2. Key idea

Code costs money when it changes: whoever edits it (person or agent) must find every related place. Per John Ousterhout, complexity comes from dependencies (a piece can't be changed alone) and obscurity (important information is hidden).

Symptom For a human reader For an AI agent
Change amplification (one change, many edits) changing the threshold touches three files edits what it sees, misses what it doesn't
Cognitive load (too much to keep in mind) call order, which flag is on, which field is null has to load many files into context
Unknown unknowns (you don't know what you need to know) the missed place surfaces two weeks later no name or type leads there

Agents find code by text search and read by name. One concept with two names (findBy, getBy) and it copies whichever it saw first, so consistency beats "most correct".

2.1 When shouldn't you follow the rule?

Technique Use when Don't use when
Extract a function // step 2 comments split it, deep nesting a 60-line linear function, no nesting, already readable
Merge duplicates (DRY) constants, business rules: merge now two similar pieces that change for different reasons; wait for the third
Interfaces, abstractions there are two real implementations "for future extension"
sealed interface + record a fixed set of variants you own plugins others extend

3. In Java

JAVA
static final long FREE_SHIPPING_THRESHOLD = 500_000;     // one place, not repeated in templates
 
boolean hasStock(String sku, int qty) {                  // named as a question; a query changes nothing
    return stock.getOrDefault(sku, 0) >= qty;
}
 
public Booking createBooking(User user, Seat seat) {     // guard clauses: edge cases first
    if (!user.active()) throw new UserInactiveException(user.id());
    if (seat.booked()) throw new SeatAlreadyBookedException(seat.number());
    return new Booking(user.id(), seat.number());        // happy path last, no indentation
}

Other languages: Go uses if err != nil { return err } as a guard clause; TypeScript uses discriminated unions instead of sealed.

4. Working with AI

Hand to AI: proposing a few names for you to pick from, splitting long functions, writing old-versus-new comparison tests before a refactor.

Check yourself in AI-written code:

  • New names say what true means and reuse the existing vocabulary (find, no new fetch).
  • Business constants aren't duplicated anymore: search the repo for the old value.
  • A "refactor only" PR keeps behavior, with an automated old-versus-new comparison.

5. Exercises

Exercise 1: Review a "no behavior change" refactor

The AI refactored feeNested into shippingFee, PR description: "Pure refactor, no behavior change". Find where behavior changed, decide whether to keep it, rewrite the PR description.

JAVA
static long feeNested(Cart c) {                 // old version
    long fee = 0;
    if (c != null) {
        if (c.country().equals("VN")) {
            if (c.subtotal() >= 500_000) fee = 0;
            else { if (c.member()) fee = 15_000; else fee = 30_000; }
            if (c.express()) fee = fee + 20_000;
        } else { fee = 200_000; if (c.express()) fee = fee + 100_000; }
    } else { fee = -1; }
    return fee;
}
 
static long shippingFee(Cart cart) {            // the AI's version
    Objects.requireNonNull(cart, "cart");
    if (!cart.country().equals("VN")) return 200_000 + (cart.express() ? 100_000 : 0);
    long base = cart.subtotal() >= FREE_SHIPPING_THRESHOLD ? 0 : (cart.member() ? 15_000 : 30_000);
    return base + (cart.express() ? 20_000 : 0);
}
Solution 1

Run both over 40 combinations (5 subtotals around the threshold, 2 countries, member or not, express or not): identical.

There's one behavior change: a null cart now throws NullPointerException instead of returning -1. Keep it, because -1 as a fee is a bug waiting to happen (someone adds it to a total). But the PR description is wrong: state "a null cart now throws NPE instead of returning -1", in a separate commit from the "refactor only" one.

Exercise 2: Choose between two designs

A SQL generator has a class producing SELECT; now it needs UPDATE. The AI offers: (A) UpdateGenerator extends SelectGenerator; (B) sealed interface SqlStatement with sibling records Select, Update. Pick one, explain, and say when an open interface beats sealed.

Solution 2

Pick B. (A) says "an UPDATE is a SELECT": wrong meaning, breaks Liskov, and UpdateGenerator inherits methods that don't apply. With (B), adding Insert to permits makes the compiler point at every switch missing a case.

Use an open interface when others must add new kinds (plugins, libraries) without editing your code. The price is losing the compiler's exhaustiveness check: each kind must carry its own behavior through the interface's methods.

Summary

  • Readable code lowers the cost of change, for people and AI alike.
  • Three symptoms: change amplification, cognitive load, unknown unknowns.
  • Consistency over "most correct"; name booleans as questions.
  • Merge business constants now; wait for the third copy of other duplicates.
  • Reviewing an AI refactor: find every behavior change, require an old-versus-new comparison.

Further reading: Error handling, boundaries and refactoring.

Practice interview questions on this topic

All OOP & Design questions →

Loading comments…