Skip to lesson

Practice: clean code

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

A teammate hands you a method that works, but nobody dares to touch it. Four mistakes cause most of that fear; each section below shows one, with its fix.

Mistake 1: names and magic numbers hide the rules

Code such as r(st, days, amt, cat, opened) with 10, 500 and 0.05 inside forces every reader to reverse-engineer the return policy. The rules exist, but only in the author's head.

Example 1 · Cleaning up a return-policy method, results unchanged

ReturnsCleanupDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;
public class ReturnsCleanupDemo {    // ---- Before: vague names, magic numbers, three levels of nesting ----    static String r(String st, int days, BigDecimal amt, String cat, boolean opened) {        if (st.equals("DELIVERED")) {            if (days <= 10) {                if (cat.equals("ELECTRONICS") && opened) {                    return "No return: opened electronics";                } else {                    BigDecimal fee = amt.compareTo(new BigDecimal("500")) < 0 ? BigDecimal.ZERO                            : amt.multiply(new BigDecimal("0.05")).setScale(2, RoundingMode.HALF_UP);                    return "Refund Rs " + amt.subtract(fee);                }            } else {                return "No return: window closed";            }        } else {            return "No return: not delivered";        }    }
    // ---- After: guard clauses, named rules, one level of detail ----    static final int RETURN_WINDOW_DAYS = 10;    static final BigDecimal FEE_FREE_BELOW = new BigDecimal("500");    static final BigDecimal RESTOCKING_FEE_RATE = new BigDecimal("0.05");
    static String returnDecision(String status, int daysSinceDelivery, BigDecimal paid, String category,                                 boolean opened) {        if (!status.equals("DELIVERED")) {            return "No return: not delivered";        }        if (daysSinceDelivery > RETURN_WINDOW_DAYS) {            return "No return: window closed";        }        if (isOpenedElectronics(category, opened)) {            return "No return: opened electronics";        }        return "Refund Rs " + paid.subtract(restockingFee(paid));    }
    static boolean isOpenedElectronics(String category, boolean opened) {        return category.equals("ELECTRONICS") && opened;    }
    static BigDecimal restockingFee(BigDecimal paid) {        if (paid.compareTo(FEE_FREE_BELOW) < 0) {            return BigDecimal.ZERO;        }        return paid.multiply(RESTOCKING_FEE_RATE).setScale(2, RoundingMode.HALF_UP);    }
    public static void main(String[] args) {        Object[][] cases = {                {"DELIVERED", 3, "499.00", "BOOKS", true},                {"DELIVERED", 10, "1299.00", "ELECTRONICS", false},                {"DELIVERED", 4, "1299.00", "ELECTRONICS", true},                {"DELIVERED", 11, "399.00", "BOOKS", false},                {"SHIPPED", 0, "2499.00", "FASHION", false}};        for (Object[] c : cases) {            String before = r((String) c[0], (Integer) c[1], new BigDecimal((String) c[2]), (String) c[3], (Boolean) c[4]);            String after = returnDecision((String) c[0], (Integer) c[1], new BigDecimal((String) c[2]),                    (String) c[3], (Boolean) c[4]);            System.out.println(after + (before.equals(after) ? "" : "   <- CHANGED from: " + before));        }    }}
Output
Refund Rs 499.00
Refund Rs 1234.05
No return: opened electronics
No return: window closed
No return: not delivered

What this code does

  • Same five answers before and after (no "CHANGED" lines), but the new method reads as the policy: not delivered, too late, opened electronics, otherwise refund minus the restocking fee.
  • Each rule now has a name and one home, so "make the window 15 days" or "no fee below Rs 1000" is a one-line change.

Rename to intent (returnDecision, daysSinceDelivery), turn each number into a named rule (RETURN_WINDOW_DAYS), replace nesting with guard clauses, and extract each idea into a small method. Check the result against the old code on the same inputs.

Mistake 2: refactoring without a safety net

"Just a small tidy-up" is how < becomes <= and a fee disappears for orders of exactly Rs 500. Without tests, nobody notices until customers do.

Example 2 · A boundary check catches a slip in a "tidy-up"

SlipCaughtDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;
public class SlipCaughtDemo {    static BigDecimal feeToday(BigDecimal paid) {        return paid.compareTo(new BigDecimal("500")) < 0 ? BigDecimal.ZERO                : paid.multiply(new BigDecimal("0.05")).setScale(2, RoundingMode.HALF_UP);    }
    // "Just a tidy-up": a constant was extracted... and <= slipped in instead of <    static final BigDecimal FEE_FREE_BELOW = new BigDecimal("500");
    static BigDecimal feeTidied(BigDecimal paid) {        if (paid.compareTo(FEE_FREE_BELOW) <= 0) {            return BigDecimal.ZERO;        }        return paid.multiply(new BigDecimal("0.05")).setScale(2, RoundingMode.HALF_UP);    }
    public static void main(String[] args) {        String[] amounts = {"499.00", "499.99", "500.00", "1299.00"};   // boundary values on purpose        int failures = 0;        for (String a : amounts) {            BigDecimal expected = feeToday(new BigDecimal(a));            BigDecimal actual = feeTidied(new BigDecimal(a));            boolean same = expected.compareTo(actual) == 0;            if (!same) {                failures++;            }            System.out.println((same ? "PASS " : "FAIL ") + "fee on Rs " + a + ": expected " + expected + ", got " + actual);        }        System.out.println(failures == 0 ? "Safe to commit" : "Undo the last step: " + failures + " check(s) red");    }}
Output
PASS fee on Rs 499.00: expected 0, got 0
PASS fee on Rs 499.99: expected 0, got 0
FAIL fee on Rs 500.00: expected 25.00, got 0
PASS fee on Rs 1299.00: expected 64.95, got 64.95
Undo the last step: 1 check(s) red

What this code does

  • Extracting the constant was fine; changing < to <= was not. Only the check at exactly Rs 500.00 noticed, because boundary values were chosen on purpose.
  • With a test run after each small step, the fix is "undo the last step", which takes seconds.

Write characterisation checks first, with boundary inputs (499.99, 500.00), make one small change, run the checks, and commit only when they are green. A red check means undo the last step, not debug a big change.

Mistake 3: trusting the coverage number

Two test suites can both reach 100% branch coverage while one of them misses every off-by-one bug. Coverage says which code ran, not whether results were checked at the right places.

Example 3 · Same coverage, very different suites

SuiteJudgeDemo.javaJava
import java.util.List;import java.util.function.IntPredicate;
public class SuiteJudgeDemo {    /** Rule: returnable within 10 days of delivery. */    static boolean returnable(int days) {        return days <= 10;    }
    // Mutants: the bugs a careless edit could bring in    static final List<String> MUTANT_NAMES = List.of("days < 10", "days <= 11", "always true");    static final List<IntPredicate> MUTANTS = List.of(d -> d < 10, d -> d <= 11, d -> true);
    record Case(int days, boolean expected) {    }
    static void judge(String suiteName, List<Case> suite) {        boolean seenTrue = suite.stream().anyMatch(c -> returnable(c.days()));        boolean seenFalse = suite.stream().anyMatch(c -> !returnable(c.days()));        int branches = (seenTrue ? 1 : 0) + (seenFalse ? 1 : 0);        int killed = 0;        for (IntPredicate mutant : MUTANTS) {            boolean caught = suite.stream().anyMatch(c -> mutant.test(c.days()) != c.expected());            if (caught) {                killed++;            }        }        System.out.printf("%-26s branch coverage %d/2, mutants killed %d/%d%n", suiteName, branches, killed, MUTANTS.size());    }
    public static void main(String[] args) {        judge("Suite A: days 2 and 30", List.of(new Case(2, true), new Case(30, false)));        judge("Suite B: days 9, 10, 11", List.of(new Case(9, true), new Case(10, true), new Case(11, false)));        System.out.println("Mutants: " + MUTANT_NAMES);    }}
Output
Suite A: days 2 and 30     branch coverage 2/2, mutants killed 1/3
Suite B: days 9, 10, 11    branch coverage 2/2, mutants killed 3/3
Mutants: [days < 10, days <= 11, always true]

What this code does

  • Both suites reach both branches of days <= 10, so a coverage report rates them equally. Suite A, far from the limit, catches only the crudest mutant.
  • Suite B tests 9, 10 and 11 days, around the boundary, and kills all three mutants. Better tests come from better inputs, not more coverage.

Judge a suite by its inputs and assertions: does it test just below, at and just above each limit? A quick mental mutation test helps: "if someone changed <= to < here, would a test fail?"

Mistake 4: ignoring what the tools report

Optional.get() on a missing order, == on Integer ids and a switch without break are all reported by SonarQube for IDE or -Xlint the moment they are typed. Ignoring the warnings turns them into 500 errors and wrong labels in production.

Example 4 · Three tool findings, fixed

FindingsFixedDemo.javaJava
import java.util.Map;import java.util.Objects;import java.util.Optional;
public class FindingsFixedDemo {    static final Map<Integer, Integer> ORDER_OWNER = Map.of(17, 1, 1018, 1001);
    // Finding 1 (Optional.get): an unknown order became NoSuchElementException -> 500    static Optional<Integer> ownerOf(int orderId) {        return Optional.ofNullable(ORDER_OWNER.get(orderId));    }
    static String canView(int orderId, Integer customerId) {        Integer owner = ownerOf(orderId).orElse(null);        if (owner == null || !Objects.equals(owner, customerId)) {    // Finding 2: was owner == customerId            return "404 Order " + orderId + " was not found";        }        return "200 Order " + orderId;    }
    // Finding 3 (fall-through): arrow switch instead of case/break    static String statusLabel(String status) {        return switch (status) {            case "PLACED" -> "Placed";            case "SHIPPED" -> "On the way";            default -> status;        };    }
    public static void main(String[] args) {        System.out.println(canView(17, 1));        System.out.println(canView(1018, 1001));        System.out.println(canView(1018, 2));        System.out.println(canView(99, 1));        System.out.println(statusLabel("PLACED"));    }}
Output
200 Order 17
200 Order 1018
404 Order 1018 was not found
404 Order 99 was not found
Placed

What this code does

  • Optional.orElse(null) plus a guard turns an unknown order into a clean 404 instead of a NoSuchElementException, and Objects.equals makes customer 1001's check work.
  • The arrow switch cannot fall through, so PLACED is labelled correctly.

Fix findings as they appear, and suppress only narrowly with a reason. Combine the tools with review: tools catch patterns, people catch wrong rules.

Finish up

Mark complete & continue

Next: Mini project: refactor the ShopLite order service