Skip to content
notes.vinhnq.com

Search

OOP & DesignMid19 min read

Clean code: why it matters, naming, functions and control flow

Review 18 cards
On this page

Clean code series: 1. Naming, functions and control flow · 2. Error handling, boundaries and refactoring

Everyone recognises clean code when they see it; the hard part is turning that gut feeling into rules a whole team can apply, and knowing when not to follow them. This post goes from the economics, through where messy code comes from (complexity), to naming, functions, classes and control flow. Part 2 covers error handling, boundaries, tests and a full refactoring session.

1. Why clean code

Key idea: because of the cost of change. Quick-and-dirty code is cheaper for a few weeks, then every feature costs more and breaks more things nearby; that is the shared root of too many bugs and slow time to market.

The cost of clean code grows close to linearly, dirty code almost exponentially; the curves cross after weeks, not years. Brian Foote and Joseph Yoder: if you think good architecture is expensive, try bad architecture.

The course makes it concrete with four “-ables”:

  • Readable: a newcomer understands a function without asking the author.
  • Maintainable: changing one business rule touches one place.
  • Testable: the logic can be tested without a database, Kafka or a real clock.
  • Scalable (as a codebase): adding people and features does not slow everyone down.

The end goal, as in Robert C. Martin’s clean architecture, is to minimise the human effort needed to build and maintain the system; clean code is only a means.

When clean code meets performance or deadlines

2. Where messy code comes from: complexity

Key idea: for John Ousterhout (A Philosophy of Software Design), complexity is anything that makes code hard to understand or modify. It comes from dependencies and obscurity, and shows up as three symptoms.

The slide’s second root is subjective: a missing sense of beauty (not asking “why”, not reading code).

graph TD
  S[Code smell] --> C[Complexity]
  S --> B[Missing sense of beauty]
  C --> D[Dependencies]
  C --> O[Obscurity]
  D --> CA((Change amplification))
  D --> CL((Cognitive load))
  O --> I[Inconsistency]
  I --> UU((Unknown unknowns))
  B --> W((Not asking why))
  B --> R((Not reading))
Meaning Example
Dependencies (cause) code can’t be understood or changed in isolation the free-shipping threshold 500_000 hard-coded in a controller, the pricing service and an email template
Obscurity (cause) important information is not obvious a status field of type int; nobody remembers what 3 means
Change amplification a simple change needs edits in many places changing the threshold means editing three files
Cognitive load you must hold too much in your head to change safely call order, which flag is set where, which field can be null
Unknown unknowns you don’t know what you need to know (the worst) two weeks later you find a fourth place using the old constant

3. How to practise

Key idea: practise along the two halves of the definition. Easy to understand: naming, conventions, formatting, code review, static analysis (Checkstyle, Sonar, Error Prone). Easy to change: design principles, design patterns, unit tests, refactoring.

KISS has two halves: break the problem into pieces small enough to understand, and don’t over-engineer (build more than you need). An interface with a single implementation “for future extension” rarely pays for itself. Robert C. Martin: if Open-Closed is the goal, Dependency Inversion is the primary mechanism. OCP through Strategy is in design patterns through refactoring, DIP in IoC and DI; this post only applies SRP and OCP at class level.

How to practise, and the coding routine the course suggests
  • Read good code (Spring Framework, the Kafka client, Guava; the KafkaProducerMetrics class reads in one pass) and books to build a sense of beauty.
  • Be disciplined but pragmatic.
  • Practise on real complexity: learn the domain, fix symptoms as soon as you see them, refactor often, pair program.

The coding routine:

  1. Write the names of the main steps first, like a table of contents.
  2. Implement the steps.
  3. Re-read and partially refactor before you even run it, while the context is fresh.
  4. Unit test, open a small merge request.
  5. Optionally refactor further for cleanliness or speed (with measurements).

4. Naming

Key idea: names are the only documentation every reader actually reads (Phil Karlton: the two hard things are cache invalidation and naming). Good names state a role or an action, distinguish by attribute, and use one word per concept.

  • Meaningful: classes are nouns describing a role (DiscountCalculator, not DiscountManager), methods are verbs (reserveSeat).
  • Distinguish by attribute: Cache with LocalCache, RemoteCache; CacheImpl or ICache says nothing about the difference.
  • Avoid vague names: data, info, tmp, msg1/msg2 (probably requestMessage/replyMessage).
  • Pronounceable: generationTimestamp, not genymdhms.
  • No type prefixes: strName, listUsers become lies when the type changes. Write users, ordersById.
  • Consistent vocabulary: if repositories use find, don’t use get or fetch elsewhere for the same thing.

The slide exercise: scope vs isScope

Key idea: the slide calls boolean isScope = checkScope(); good and boolean scope = ... bad. is tells you it’s a boolean, but still not scope of what, or what true means.

5. Functions

Key idea: a function reads top to bottom like a story, does one thing, and never both changes state and answers. “40 lines, 3 parameters” is only a heuristic.

  • Stepdown rule: high-level functions first, the functions they call right below; readers stop at the detail level they need.
  • Do one thing = one reason to change. No surprising side effects: isValidPassword must not quietly create a session.
  • CQS (Command Query Separation): a method either does something (a command, returns void) or answers something (a query, changes no state), never both.
// Breaks CQS: sounds like a query but decrements stock
boolean checkAndReserve(String sku, int qty) {
    int left = stock.getOrDefault(sku, 0);
    if (left < qty) return false;
    stock.put(sku, left - qty);
    return true;
}

// Split: the query changes nothing, the command fails loudly with context
boolean hasStock(String sku, int qty) {
    return stock.getOrDefault(sku, 0) >= qty;
}

void reserve(String sku, int qty) {
    int left = stock.getOrDefault(sku, 0);
    if (left < qty) {
        throw new IllegalStateException("Not enough stock for " + sku + ": need " + qty + ", have " + left);
    }
    stock.put(sku, left - qty);
}

reserve still re-checks, because two threads can both see hasStock return true. That is also why Map.putIfAbsent, AtomicInteger.incrementAndGet and Queue.poll deliberately combine query and command: splitting them creates a race between asking and acting. CQS is a rule for business code, not for concurrency primitives.

  • Small: the course says about 40 lines, one switch, at most 3 parameters. A 60-line sequential function with no nesting can be easier to read than five 12-line functions that jump around. Real signals to split: // step 2 comments carving the body into chunks, or deep nesting. More than 3 parameters usually want a record.
  • Prefer pure functions (same input, same output, no clock, no database): one-line assertEquals tests, safe in parallel. The shape: “functional core, imperative shell”.
  • Avoid deep nesting, of both ifs and callbacks (section 8).
  • DRY is about knowledge, not characters: two identical snippets that change for different reasons are not duplication.

6. Classes

Key idea: small classes with one responsibility; trying to name the class is the cheapest test. Add new variants as sibling classes, not by subclassing the old one.

SRP through the name. If the most natural name is OrderManager, OrderHelper or needs an “And”, the class does too much. Class A on the slide (constants DOMAIN, PORT, a mutable static String name field, method1() to method4()) can’t get a good name because it has no clear responsibility.

Open-Closed: organising for change. The slide: class A generates SELECT statements, now we need UPDATE; the proposed solution is B extends A.

In Java 21 the most compact way is a sealed interface (an interface that allows only a fixed list of implementing classes) plus records:

sealed interface SqlStatement permits Select, Update {
    String toSql();
}

record Select(String table, List<String> columns, String where) implements SqlStatement {
    public String toSql() {
        String sql = "SELECT " + String.join(", ", columns) + " FROM " + table;
        return where == null ? sql : sql + " WHERE " + where;
    }
}

record Update(String table, Map<String, String> assignments, String where) implements SqlStatement {
    Update {
        if (where == null || where.isBlank()) {
            throw new IllegalArgumentException("UPDATE without WHERE is not allowed");
        }
    }
    public String toSql() {
        String set = assignments.entrySet().stream()
                .map(e -> e.getKey() + " = " + e.getValue())
                .collect(Collectors.joining(", "));
        return "UPDATE " + table + " SET " + set + " WHERE " + where;
    }
}

Update rejects a missing WHERE in its own compact constructor. To branch on the type, use switch (statement) { case Select s -> ...; case Update u -> ...; } with no default. Add Delete and the compiler flags every switch that doesn’t handle it: change amplification with the compiler as your guide, instead of unknown unknowns.

Sealed or open interface: the expression problem

7. One level of abstraction per function

Key idea: every statement in a function should sit at the same level of abstraction (SLAP, Single Level of Abstraction Principle). The main function speaks the business language; technical detail lives one level down.

The slide uses a long createPizza function: make the base, choose toppings by kind, loop until the oven is hot, bake, box, slice, all in one block. After refactoring, the main function has three steps:

static Pizza createPizza(Order order) {
    Pizza pizza = prepare(order);
    bake(pizza);
    box(pizza);
    return pizza;
}

static Pizza prepare(Order order) {
    Pizza pizza = new Pizza(order.size());
    pizza.toppings = toppingsFor(order.kind());   // a switch on VEG/MEAT
    return pizza;
}

Oven temperatures and the wait loop live in bake. Like a book’s table of contents: it lists chapter titles, not the chapters’ text.

8. Flattening control flow

Key idea: stop edge cases at the top of the function, and move branching into helper functions.

Guard clauses: handle the edge cases first

Key idea: a guard clause checks an edge case at the top and returns or throws immediately, replacing an if / else if / else chain that hides the happy path in the else.

The slide’s createBooking, rewritten in Java with a few leftovers fixed:

// Before: happy path pushed into else, errors only printed, then null returned
public Booking createBooking(User user, Seat seat) {
    if (user.getStatus() == false) {
        System.out.println("User is not active");
    } else if (seat.isBooked() == true) {
        System.out.println("Seat is already booked");
    } else {
        return new Booking(user.id(), seat.number());
    }
    return null;
}

// After: guard clauses, domain exceptions, happy path last and unindented
public Booking createBooking(User user, Seat seat) {
    if (!user.active()) throw new UserInactiveException(user.id());
    if (seat.booked()) throw new SeatAlreadyBookedException(seat.number());
    return new Booking(user.id(), seat.number());
}

Fewer structures for the reader to hold

Key idea: move branching into a named helper. The total barely shrinks, but each place the reader looks at is smaller.

Two more techniques: extract long conditions into named methods (isEligibleForRefund(order)), and replace an if / else if chain on one variable with a switch expression. Control-flow refactors should always come with an automated old-vs-new comparison.

The Google Testing Blog example: a hotel-room loop

The slide comes from “Write Clean Code to Reduce Cognitive Load” (Google Testing Blog, 2023): a while loop holding an if / else if plus an if with a break (5 structures, 9 edges) is harder to retain than a loop that calls one helper (3 structures, 5 edges) plus the helper itself (2 structures, 4 edges). A similar example:

// Before: one loop both chooses the service action and handles alerts
for (Room r : rooms) {
    if (!r.occupied()) continue;
    if (r.vip()) {
        log.add("warm");
    } else if (r.guestOnPhone()) {
        log.add("quiet");
    }
    if (r.hasAllergyRisk()) {
        log.add("alert");
        break;
    }
}

// After: the loop tells the story, the helper owns the choice
for (Room room : rooms) {
    if (!room.occupied()) continue;
    comfortAction(room).ifPresent(log::add);
    if (room.hasAllergyRisk()) {
        log.add("alert");
        break;
    }
}

static Optional<String> comfortAction(Room room) {
    if (room.vip()) return Optional.of("warm");
    if (room.guestOnPhone()) return Optional.of("quiet");
    return Optional.empty();
}

I ran both versions on 2,000 randomly generated sets of rooms and compared the output: identical.

Exercises

All code in sections 5 to 8 and both exercises was run on JDK 21 with automated checks.

Exercise 1: Rename

Task (my own, in the spirit of the slide): rename this so it needs no comment.

// returns active users who logged in within d days
List<User> get(List<User> l, int d) {
    List<User> r = new ArrayList<>();
    for (User u : l) if (u.getS() == 1 && u.getLl().isAfter(LocalDate.now().minusDays(d))) r.add(u);
    return r;
}
Solution to Exercise 1
List<User> activeUsersLoggedInWithin(List<User> users, Duration window, LocalDate today) {
    LocalDate cutoff = today.minusDays(window.toDays());
    return users.stream()
            .filter(User::isActive)
            .filter(user -> user.lastLoginDate().isAfter(cutoff))
            .toList();
}

getS() == 1 (a magic number) becomes isActive(), int d becomes a Duration so the type carries the unit, and LocalDate.now() becomes a today parameter so the function is pure and testable. The comment is now redundant.

Exercise 2: Flatten the shipping fee

Task: this function nests four levels deep and returns -1 for a null cart. Flatten it, keeping results identical for valid input.

static long feeNested(Cart c) {
    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;
}
Solution to Exercise 2
static final long FREE_SHIPPING_THRESHOLD = 500_000;

static long shippingFee(Cart cart) {
    Objects.requireNonNull(cart, "cart");
    if (!cart.country().equals("VN")) return 200_000 + (cart.express() ? 100_000 : 0);
    return domesticBaseFee(cart) + (cart.express() ? 20_000 : 0);
}

static long domesticBaseFee(Cart cart) {
    if (cart.subtotal() >= FREE_SHIPPING_THRESHOLD) return 0;
    return cart.member() ? 15_000 : 30_000;
}

I ran both functions on 40 combinations (5 subtotals around the threshold, 2 countries, member or not, express or not): identical.

There is one deliberate behaviour change: a null cart now throws NullPointerException instead of returning -1. A magic -1 fee is a bug waiting to happen (someone adds it to the order total). Changes like that must be called out in the PR and go in their own commit, not mixed into a “pure refactor” commit.

Remember

  • Explain why dirty code is only cheaper for the first few weeks, and name the four “-ables”.
  • Name the three symptoms of complexity and explain why inconsistency breeds unknown unknowns.
  • Name a boolean after its question, and say why a boolean checkX() is a bad name.
  • Explain CQS and why putIfAbsent breaks it on purpose.
  • Know when to merge duplicates (rule of three, constants immediately) and when to use a sealed interface instead of inheritance.

Interview questions

Junior

What is clean code, and why should a business care?

Code that is easy to understand and easy to change; a business cares because it keeps the cost per change low.

Dirty code is cheap for a few weeks, then every feature costs more, bugs multiply and time to market slips. The goal is to minimise the human effort to build and maintain the system.

How do you name a boolean well?

After the question the value answers, usually with is, has or can: emailVerified, hasScope, canRefund.

Avoid neutral names like flag and negatives like notDisabled. A boolean method shouldn’t be called checkX(), because it doesn’t say what true means.

What is a guard clause?

A check for an edge case at the top of a function that returns or throws immediately, so the happy path sits at the end without indentation.

It replaces nested if / else if / else chains and makes the function read top to bottom.

Mid

What is Command Query Separation, and are there exceptions?

A method either changes state (a command) or returns information (a query), never both; atomic operations are the exception.

Calling a query any number of times is safe. Deliberate exceptions are putIfAbsent, incrementAndGet and poll: splitting them would create a race between asking and acting.

What are Ousterhout’s three symptoms of complexity?

Change amplification, cognitive load and unknown unknowns (the worst).

Change amplification: a simple change needs edits in many places. Cognitive load: you must remember a lot to change things safely. Unknown unknowns: you don’t know what you need to know. The causes are dependencies and obscurity; inconsistency is the main source of unknown unknowns.

Is DRY always right?

No. DRY is about knowledge, not characters.

Two identical snippets that change for different reasons shouldn’t be merged; merging early produces wrong abstractions full of boolean flags. In practice I use the rule of three, but business rules and constants get merged immediately.

How can you tell a class violates SRP?

Try naming it: if the most natural name is Manager or Helper, or needs an “And”, it does too much.

Other signs: it changes for unrelated reasons, its tests need too many mocks, groups of methods use disjoint groups of fields.

Senior

The slide adds UPDATE support by subclassing the SELECT generator. What would your review comment be?

The inheritance is wrong in meaning (an UPDATE is not a kind of SELECT) and breaks Liskov; use siblings under a common abstraction.

Code expecting a SELECT generator may receive one that emits UPDATE, and the subclass drags along fields it doesn’t use. In Java 21 that is a sealed interface SqlStatement with records and a pattern-matching switch so the compiler checks exhaustiveness.

How do cognitive and cyclomatic complexity differ, and how do you use them?

Cyclomatic counts independent paths (a test estimate); cognitive adds increments for nesting depth, so it tracks readability better.

Cyclomatic doesn’t distinguish a flat switch from nested ifs. I set a cognitive complexity threshold (Sonar’s default for Java is 15) as a quality gate on new code, without forcing a rewrite of old code.

How would you bring clean code into a team with a legacy codebase?

Not with a rewrite; improve it gradually, backed by tooling and tests.

Put a few conventions into tooling (formatter, a quality gate on new code only), leave code a bit cleaner every time you touch it, refactor behind characterization tests and keep refactoring commits separate from behaviour changes. Prioritise the files that change most often according to git history, where complexity costs the most.

Useful phrases for interviews

  • “I treat clean code as a way to keep the cost of the next change low, not as an aesthetic goal.”
  • “This method mixes two levels of abstraction, so I’d extract the low-level part behind a name.”
  • “Duplication is cheaper than the wrong abstraction, so I wait for a third occurrence before merging.”
  • “A guard clause keeps the happy path at the lowest indentation level.”
  • “The name checkScope doesn’t tell me what true means; I’d rename it after the question it answers.”
  • “This breaks command-query separation: it reads like a query but it mutates state.”
  • “I’d model these variants as a sealed interface so the compiler tells us every place to update.”
  • “We gate new code on cognitive complexity rather than trying to fix the whole legacy codebase at once.”

Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.