SyntaxPilot
Courses/Low-Level Design/Lesson 51
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 51 of 90

Clean code: naming, functions and code smells

clean codemeaningful namessmall functionssingle level of abstractioncommand-query separationside effectscomments vs self-documenting codemagic numbersconstantscode smellslong methodlarge classprimitive obsessionfeature envy

These are the notes for Low-Level Design (LLD) episode 51, the first episode of the code-quality block. Code that works is not enough: in a machine-coding round the interviewer also reads your code, and in a real team many people will change it after you. We invent clean code step by step at Ravi's canteen: meaningful names, named constants instead of magic numbers, small functions at a single level of abstraction, command-query separation and side effects, comments vs self-documenting code, and the code smells that warn you a design is going wrong: long method, large class, primitive obsession, feature envy, data clumps, shotgun surgery, divergent change and long parameter list. Every program was actually run with javac Main.java && java -cp . Main (Java 21), and every output shown is the real output.

1. The real-life idea: a recipe someone else must cook from

In a kitchen In code
"Add 2 of X, then do the thing": only the writer understands it Meaningful names: a name must say what something is
"Add 0.05 of it": 0.05 of what, and why? Magic number → named constant (TAX_RATE)
Short steps: boil water, add tea, add milk Small functions: one job each
A smell of burning: not proof, but go and look Code smell: a surface hint of a deeper design problem

Clean code means code that another person can read, understand and change without fear. Code is read many more times than it is written, so we write it for the reader.

2. The problem: code that works but can't be changed

Ravi's teammate wrote the billing function:

public class Main {
    static double c(int[] q, double[] p, int d, boolean m) {
        double s = 0;
        for (int i = 0; i < q.length; i++) s += q[i] * p[i];
        if (m) s = s - s * 0.1;
        if (d > 3) s = s + 20;
        s = s + s * 0.05;
        System.out.println("Total: " + s);
        return s;
    }
    public static void main(String[] args) {
        c(new int[]{2, 1}, new double[]{40, 120}, 5, true);   // ???
    }
}

Output (real):

Total: 210.0

The answer happens to be right. But Ravi now says "members get 15% off from Monday". Which number do you change? Is d a distance, a day or a discount? Is m "member" or "monthly"? The code runs, but nobody can change it safely.

3. Meaningful names and named constants

A meaningful name tells you what something is without reading the code around it.

Rule Bad Good
Say what it is c, s, temp, data2 totalBill, subtotal
Put the unit in the name distance, timeout distanceKm, timeoutMs
Booleans read as yes/no questions member, flag isMember, hasPaid
Methods are verbs (they do something) tax(), sale() addTax(), recordSale()
Classes are nouns Calculate, DoBilling BillCalculator, Receipt
One word per idea across the code base fetch/get/retrieve mixed always find... for lookups

A magic number is a bare literal whose meaning is hidden (0.05, 3, 20). Replace it with a named constant: a static final field whose value never changes while the program runs and whose name explains it.

public class Main {
    static final double MEMBER_DISCOUNT = 0.10;   // 10% off for members
    static final int FREE_DELIVERY_KM = 3;
    static final double DELIVERY_FEE = 20;        // rupees
    static final double TAX_RATE = 0.05;          // 5% in our example
    static double totalBill(int[] quantities, double[] prices, int distanceKm, boolean isMember) {
        double total = 0;
        for (int i = 0; i < quantities.length; i++) total += quantities[i] * prices[i];
        if (isMember) total -= total * MEMBER_DISCOUNT;
        if (distanceKm > FREE_DELIVERY_KM) total += DELIVERY_FEE;
        total += total * TAX_RATE;
        return total;
    }
    public static void main(String[] args) {
        int[] quantities = {2, 1};                // 2 chai-samosa, 1 thali
        double[] prices = {40, 120};
        System.out.println("Total: " + totalBill(quantities, prices, 5, true));
    }
}

Output (real):

Total: 210.0

Same behaviour, but the 15% change is now one line at the top, with a name.

4. Small functions, one level of abstraction

totalBill still does five jobs in one block. The rules:

  • A function should do one thing, and its name should describe that thing completely.
  • Keep it small: it should fit on a screen, often 5–15 lines.
  • Keep a single level of abstraction in each function. Abstraction level = how much detail you are looking at. "Calculate the bill" is high level; i < q.length is low level. Don't mix them in one function: the top function should read like the recipe, and each step hides its details in its own small function.
import java.util.List;
public class Main {
    record Item(String name, int quantity, double price) { }
    record Order(List<Item> items, int distanceKm, boolean isMember) { }
    static final double MEMBER_DISCOUNT = 0.10, DELIVERY_FEE = 20, TAX_RATE = 0.05;
    static final int FREE_DELIVERY_KM = 3;

    static double totalBill(Order order) {           // reads like the recipe
        double food = applyMemberDiscount(subtotal(order), order.isMember());
        return addTax(food + deliveryFee(order.distanceKm()));
    }
    static double subtotal(Order order) {
        double sum = 0;
        for (Item item : order.items()) sum += item.quantity() * item.price();
        return sum;
    }
    static double applyMemberDiscount(double amount, boolean isMember) {
        return isMember ? amount - amount * MEMBER_DISCOUNT : amount;
    }
    static double deliveryFee(int distanceKm) { return distanceKm > FREE_DELIVERY_KM ? DELIVERY_FEE : 0; }
    static double addTax(double amount) { return amount + amount * TAX_RATE; }

    public static void main(String[] args) {
        List<Item> items = List.of(new Item("chai-samosa", 2, 40), new Item("thali", 1, 120));
        Order order = new Order(items, 5, true);
        System.out.println("Total: " + totalBill(order));
    }
}

Output (real):

Total: 210.0

Item and Order are records (small immutable data classes, episode 3). Passing an Order instead of three loose parameters is the cure for a long parameter list (section 9). Each small function can now be tested, reused and changed on its own.

5. The problem: a hidden side effect

A side effect is any change a method makes beyond returning its value: updating a field, writing a file, sending an SMS, printing.

class Canteen {
    private double salesToday = 0;
    double total(double food) {      // sounds like a question...
        double bill = food * 1.05;
        salesToday += bill;          // ...but it also CHANGES state
        return bill;
    }
    double salesToday() { return salesToday; }
}
public class Main {
    public static void main(String[] args) {
        Canteen canteen = new Canteen();
        double bill = canteen.total(200);                      // the order
        System.out.println("Receipt: " + canteen.total(200));  // print it
        System.out.println("Sales today: " + canteen.salesToday());
    }
}

Output (real):

Receipt: 210.0
Sales today: 420.0

total() sounds like a question, but asking it also adds to salesToday. Printing the receipt asked again, so one order was counted twice.

6. Command-query separation

Command-query separation (CQS): every method is either

  • a query: answers a question, changes nothing (it can be called any number of times), or
  • a command: changes something and returns nothing (void).

Never both.

class Canteen {
    private double salesToday = 0;
    double priceWithTax(double food) { return food * 1.05; }  // QUERY: answers, changes nothing
    void recordSale(double bill) { salesToday += bill; }      // COMMAND: changes, returns nothing
    double salesToday() { return salesToday; }
}
public class Main {
    public static void main(String[] args) {
        Canteen canteen = new Canteen();
        double bill = canteen.priceWithTax(200);
        canteen.recordSale(bill);                                    // once, on purpose
        System.out.println("Receipt: " + canteen.priceWithTax(200));  // ask as often as you like
        System.out.println("Sales today: " + canteen.salesToday());
    }
}

Output (real):

Receipt: 210.0
Sales today: 210.0

Now the signature tells the truth: a return value means "only answers", void means "changes something".

Well-known exceptions exist (for example Deque.pollFirst() and Iterator.next() both return a value and change state, for convenience), but in your own domain classes keep queries and commands apart unless there's a strong reason.

7. Comments vs self-documenting code

A comment that lies Self-documenting
// members get 10% off
if (m) s = s * 0.85;
if (isMember) total = applyMemberDiscount(total);
// check the order
if (d > 3 && !p && t < 2) ...
if (needsDeliveryCharge(order)) ...

The code was changed to 15%, the comment wasn't: now the comment lies, and the compiler cannot catch it. Self-documenting code uses names (of variables, methods and extracted conditions) to say what is happening, so a comment isn't needed for that.

Good comments say what the code can't:

  • why a rule exists ("tax rate from the July 2025 notice"),
  • a warning ("not thread-safe; call from the UI thread only"),
  • a link to the source of a rule, or a documented public API (Javadoc).

8. Smell: primitive obsession

Primitive obsession is using basic types (int, double, String, boolean) for ideas that have their own rules: money, phone numbers, PIN codes, email addresses, distances.

public class Main {
    public static void main(String[] args) {
        double chai = 10.10, samosa = 20.20;          // money as a plain double
        System.out.println("Bill: " + (chai + samosa));
        String phone = "98765-ABCDE";                 // phone as a plain String
        System.out.println("SMS sent to " + phone);
    }
}

Output (real):

Bill: 30.299999999999997
SMS sent to 98765-ABCDE

A double is a binary floating-point number: it stores numbers in base 2 and can't store most decimal fractions (like 0.10) exactly, so sums of rupees and paise drift. And a String accepts any text as a "phone".

The fix is a value type (also called a value object, episode 6): a small immutable type that knows its own rules.

record Money(long paise) {                       // a tiny type that knows money
    static Money rupees(long r, long p) { return new Money(r * 100 + p); }
    Money plus(Money other) { return new Money(paise + other.paise); }
    @Override public String toString() { return String.format("Rs %d.%02d", paise / 100, paise % 100); }
}
record Phone(String digits) {
    Phone {                                      // checked once, when it is made
        if (!digits.matches("[6-9][0-9]{9}"))
            throw new IllegalArgumentException("not a 10-digit mobile number: " + digits);
    }
}
public class Main {
    public static void main(String[] args) {
        Money chai = Money.rupees(10, 10), samosa = Money.rupees(20, 20);
        System.out.println("Bill: " + chai.plus(samosa));
        System.out.println("SMS sent to " + new Phone("9876543210").digits());
        new Phone("98765-ABCDE");
    }
}

Output (real):

Bill: Rs 30.30
SMS sent to 9876543210
Exception in thread "main" java.lang.IllegalArgumentException: not a 10-digit mobile number: 98765-ABCDE
    at Phone.<init>(Main.java:9)
    at Main.main(Main.java:17)

Money stores whole paise in a long, so there are no fractions to get wrong (in real systems BigDecimal is the other common choice). Phone checks itself once, in its compact constructor, so every Phone that exists is valid, and a bad value fails where it is created, not three classes later.

9. Smells: long parameter list and data clumps

public class Main {
    static String label(String name, String street, String city, String pin, String phone) {
        return name + ", " + street + ", " + city + " - " + pin + " (" + phone + ")";
    }
    public static void main(String[] args) {
        System.out.println(label("Asha", "MG Road", "Bengaluru", "560001", "9876543210"));
        System.out.println(label("Ravi", "FC Road", "411004", "Pune", "9123456780"));   // oops
    }
}

Output (real):

Asha, MG Road, Bengaluru - 560001 (9876543210)
Ravi, FC Road, 411004 - Pune (9123456780)
  • Long parameter list: a method with so many parameters (rule of thumb: more than 3–4) that callers mix them up. With five Strings, a swap compiles fine.
  • Data clump: the same group of values that always travel together but have no name (street + city + PIN).

The fix: give the clump a name, and give its values their own types.

record Pin(String value) {
    Pin { if (!value.matches("[1-9][0-9]{5}")) throw new IllegalArgumentException("bad PIN code: " + value); }
}
record Address(String street, String city, Pin pin) { }       // the clump gets a name
record Customer(String name, String phone, Address address) { }
public class Main {
    static String label(Customer c) {
        Address a = c.address();
        return c.name() + ", " + a.street() + ", " + a.city()
                + " - " + a.pin().value() + " (" + c.phone() + ")";
    }
    public static void main(String[] args) {
        Address ravis = new Address("FC Road", "Pune", new Pin("411004"));
        System.out.println(label(new Customer("Ravi", "9123456780", ravis)));
        new Address("FC Road", "411004", new Pin("Pune"));   // swapped again?
    }
}

Output (real):

Ravi, FC Road, Pune - 411004 (9123456780)
Exception in thread "main" java.lang.IllegalArgumentException: bad PIN code: Pune
    at Pin.<init>(Main.java:2)
    at Main.main(Main.java:15)

The swap is now caught immediately. Types turn silent mistakes into loud ones.

10. The code smell catalogue

A code smell is a characteristic of source code that hints at a deeper problem. It is a hint, not proof: when you notice one, go and look. The term was popularized by Kent Beck in the late 1990s and was featured in Martin Fowler's 1999 book Refactoring: Improving the Design of Existing Code.

Smell What it looks like Usual fix
Long method You must scroll to read it; comments separate "sections" Extract small methods (episode 52)
Large class (god class) One class knows and does everything; dozens of fields Split by responsibility (SRP, episode 12); extract class
Primitive obsession String phone, double price, int status Value types: Phone, Money, an enum
Data clumps street, city, pin passed together everywhere A record: Address
Long parameter list ship(a, b, c, d, e, f) Parameter object; value types; builder (episode 25)
Feature envy A method uses another object's data more than its own Move the method to that class
Shotgun surgery One change forces small edits in many classes Gather the scattered logic into one place
Divergent change One class is edited for many unrelated reasons Split the class so each part has one reason to change
Magic numbers 0.05, 3, 20 in the middle of code Named constants
Duplicated code The same lines in several places Extract a method; one source of truth

Feature envy

// Billing.java: envious, it only asks Customer questions
double discountFor(Customer c) {
  if (c.isMember() && c.visits() > 10) return 0.15;
  if (c.isMember()) return 0.10;
  return 0;
}
// Customer.java: moved home, the logic lives with its data
double discount() {
  if (isMember && visits > 10) return 0.15;
  if (isMember) return 0.10;
  return 0;
}
// billing now just asks: c.discount()

Shotgun surgery vs divergent change

  • Shotgun surgery: one change → edits in many classes. Example: the tax rate is copied into Bill, Receipt, Report and Sms; change it and you'll miss one. Fix: gather it into one place (TaxPolicy).
  • Divergent change: one class → changes for many reasons. Example: Canteen is edited for tax rules, for the SMS format and for the menu. Fix: split it (TaxPolicy, SmsFormatter, Menu).
  • The goal for both: one change touches one place.

Common mistakes

Mistake What you see (real) Why Fix
double for money Bill: 30.299999999999997 Binary fractions can't store 0.10 exactly long paise, BigDecimal, or a Money type
A query that also changes state Sales today: 420.0 for one order Hidden side effect Split into a query and a command
Five String parameters No error: Ravi, FC Road, 411004 - Pune Same type, wrong order Parameter object + value types
Unvalidated String phone No error: SMS sent to 98765-ABCDE Primitive obsession Phone record that validates; then IllegalArgumentException: not a 10-digit mobile number: 98765-ABCDE
Magic numbers No error: someone changes the wrong 0.1 Meaning hidden Named constants
Comment not updated No error: the comment lies The compiler can't check comments Names say what, comments say why
Names like data, info, manager, temp No error: nobody knows what it holds Vague names Name by role and content

Mini project: a clean canteen receipt

All the ideas together: Money (no primitive obsession), records for Item and Order (no data clumps or long parameter lists), named constants, small private functions at one level of abstraction, and queries without side effects.

import java.util.List;
record Money(long paise) {
    static Money rupees(long r) { return new Money(r * 100); }
    Money plus(Money o) { return new Money(paise + o.paise); }
    Money times(int n) { return new Money(paise * n); }
    Money percent(int p) { return new Money(paise * p / 100); }
    Money minus(Money o) { return new Money(paise - o.paise); }
    @Override public String toString() { return String.format("Rs %d.%02d", paise / 100, paise % 100); }
}
record Item(String name, int quantity, Money price) {
    Money cost() { return price.times(quantity); }
}
record Order(List<Item> items, int distanceKm, boolean isMember) { }
final class Receipt {
    private static final int MEMBER_DISCOUNT_PERCENT = 10, TAX_PERCENT = 5, FREE_DELIVERY_KM = 3;
    private static final Money DELIVERY_FEE = Money.rupees(20);

    static String print(Order order) {
        StringBuilder out = new StringBuilder();
        for (Item item : order.items()) out.append(line(item)).append('\n');
        out.append("Total: ").append(total(order));
        return out.toString();
    }
    static Money total(Order order) {
        Money food = afterDiscount(subtotal(order), order.isMember());
        return withTax(food.plus(deliveryFee(order.distanceKm())));
    }
    private static String line(Item item) { return item.quantity() + " x " + item.name() + " = " + item.cost(); }
    private static Money subtotal(Order order) {
        Money sum = new Money(0);
        for (Item item : order.items()) sum = sum.plus(item.cost());
        return sum;
    }
    private static Money afterDiscount(Money amount, boolean isMember) {
        return isMember ? amount.minus(amount.percent(MEMBER_DISCOUNT_PERCENT)) : amount;
    }
    private static Money deliveryFee(int distanceKm) { return distanceKm > FREE_DELIVERY_KM ? DELIVERY_FEE : new Money(0); }
    private static Money withTax(Money amount) { return amount.plus(amount.percent(TAX_PERCENT)); }
}
public class Main {
    public static void main(String[] args) {
        Order order = new Order(List.of(new Item("chai-samosa", 2, Money.rupees(40)), new Item("thali", 1, Money.rupees(120))), 5, true);
        System.out.println(Receipt.print(order));
    }
}

Output (real):

2 x chai-samosa = Rs 80.00
1 x thali = Rs 120.00
Total: Rs 210.00

Practice

1. Clean this up: static int f(int[] a) { int c = 0; for (int x : a) if (x >= 35) c++; return c; } (35 is the pass mark).

Answer
public class Main {
    static final int PASS_MARK = 35;
    static int countPassed(int[] marks) {
        int passed = 0;
        for (int mark : marks) if (mark >= PASS_MARK) passed++;
        return passed;
    }
    public static void main(String[] args) {
        System.out.println("passed: " + countPassed(new int[]{80, 34, 35, 12, 99}));
    }
}

Output (real):

passed: 3

2. A token queue at Ravi's counter has int next() that returns the next token and removes it, so the display screen and the counter both call it and tokens get skipped. Apply command-query separation.

Answer
import java.util.*;
class TokenQueue {
    private final Deque<Integer> waiting = new ArrayDeque<>(List.of(101, 102, 103));
    int peekNext() { return waiting.peekFirst(); }        // query: no change
    void callNext() { waiting.pollFirst(); }               // command: changes, returns nothing
    int waitingCount() { return waiting.size(); }
}
public class Main {
    public static void main(String[] args) {
        TokenQueue q = new TokenQueue();
        System.out.println("next: " + q.peekNext() + ", next again: " + q.peekNext());
        q.callNext();
        System.out.println("after calling: next " + q.peekNext() + ", waiting " + q.waitingCount());
    }
}

Output (real):

next: 101, next again: 101
after calling: next 102, waiting 2

3. Customers' emails are stored as String, and some contain spaces, capitals or no @. Replace the primitive with a value type.

Answer
record Email(String value) {
    Email {
        value = value.trim().toLowerCase();
        if (!value.matches("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}"))
            throw new IllegalArgumentException("not an email address: " + value);
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new Email("  Asha@Example.COM ").value());
        System.out.println(new Email("asha.example.com").value());
    }
}

Output (real):

asha@example.com
Exception in thread "main" java.lang.IllegalArgumentException: not an email address: asha.example.com
    at Email.<init>(Main.java:5)
    at Main.main(Main.java:11)

4. Name the smell: (a) adding a new payment method needs edits in Checkout, Invoice, Refund, Report and Email; (b) OrderManager was edited this month for pricing, for PDF layout and for database columns; (c) Invoice.lateFee(Customer c) reads c.plan(), c.joinDate() and c.region() and nothing of Invoice.

Answer

(a) shotgun surgery; (b) divergent change (and probably a large class); (c) feature envy: move lateFee to Customer (or a policy class Customer uses).

5. Which of these comments are worth keeping? (a) // add one to i above i++ (b) // Bank API rejects amounts above Rs 1,00,000 per call, so we split payments (c) // loop over items

Answer

Only (b): it explains why, which the code can't say. (a) and (c) repeat what the code already says, and will rot.

Quick quiz

void ship(String street, String city,
          String pin, String phone,
          String name, boolean express)

Which smell is this? (a) Feature envy (b) Long parameter list and a data clump (c) Shotgun surgery (d) Divergent change

Answer

(b). Six parameters, five of the same type, and street + city + PIN always travel together. Group them into an Address record (with a Pin type), and make the phone a Phone.

Interview questions

  1. What makes code "clean"? It's easy to read, easy to change safely, and does what its names say: meaningful names, small focused functions, no hidden side effects, no duplication, tests.
  2. What is a magic number and how do you fix it? A literal with a hidden meaning; replace it with a well-named constant (or an enum or a configuration value).
  3. What is command-query separation? A method either returns information (query, no side effects) or changes state (command, returns nothing), never both.
  4. When should you write a comment? For why: reasons, warnings, references, public API docs. Not for what: make the code say that.
  5. What is primitive obsession? Give an example. Basic types standing for domain ideas, e.g. double for money (30.299999999999997); fix with value types that validate and behave.
  6. Feature envy vs shotgun surgery vs divergent change? A method in the wrong class / one change, many classes / one class, many reasons to change.
  7. Why not use double for money? Binary floating point can't represent most decimal fractions exactly; use integer paise or BigDecimal.
  8. What does "single level of abstraction" mean? A function's statements are all at the same level of detail; details live in the functions it calls.

Glossary

Term Meaning, with an example
Clean code Code a teammate can read, understand and change without fear
Meaningful name A name that says what something is: distanceKm, not d
Magic number A bare literal with hidden meaning: 0.05 in the middle of a calculation
Constant A value that never changes while the program runs: static final double TAX_RATE = 0.05;
Named constant A constant whose name explains the value: MEMBER_DISCOUNT
Small function A function that does one job and fits on a screen: addTax(amount)
Level of abstraction How much detail you're looking at: "calculate the bill" (high) vs a loop index (low)
Single level of abstraction All statements in a function are at the same level of detail
Side effect A change a method makes beyond returning its value: updating salesToday, printing, sending an SMS
Query A method that returns information and changes nothing: priceWithTax(200)
Command A method that changes state and returns nothing: void recordSale(double bill)
Command-query separation (CQS) Every method is a query or a command, never both
Comment Text in code ignored by the compiler: // why this rule exists
Self-documenting code Code whose names explain what it does without comments: if (needsDeliveryCharge(order))
Record A compact immutable data class: record Item(String name, int quantity, double price) { }
Compact constructor A record constructor without a parameter list, used to validate: Phone { if (...) throw ...; }
Value type (value object) A small immutable type for a domain value, compared by its content: Money, Phone
Binary floating point (double) Numbers stored in base 2; most decimal fractions are approximated: 10.10 + 20.20 = 30.299999999999997
Code smell A surface sign that hints at a deeper design problem: a 200-line method
Long method A method too long to understand at a glance
Large class (god class) A class that knows and does too much
Primitive obsession Using int/double/String for domain ideas: String phone
Feature envy A method more interested in another class's data than its own
Data clump A group of values that always travel together without a name: street, city, PIN
Long parameter list Too many parameters, easy to pass in the wrong order
Shotgun surgery One change requires edits in many classes
Divergent change One class changes for many different reasons
Duplicated code The same logic written in more than one place
IllegalArgumentException The standard Java exception for a bad argument: not a 10-digit mobile number: 98765-ABCDE
Refactoring Changing the structure of code without changing its behaviour (next episode)

Summary

  • Working code isn't enough: clean code is easy to read and safe to change.
  • Use meaningful names (units, yes/no booleans, verb methods) and named constants instead of magic numbers.
  • Write small functions that do one thing at a single level of abstraction; the top function reads like the recipe.
  • Command-query separation: a method answers or changes, never both; side effects hidden behind innocent names cause bugs like double counting.
  • Names say what, comments say why; comments that repeat the code eventually lie.
  • Learn the code smells: long method, large class, primitive obsession, data clumps, long parameter list, feature envy, shotgun surgery, divergent change. A smell is a hint to go and look.

Next episode: Refactoring techniques: extract method, inline, rename, introduce parameter object, encapsulate field, move method, extract class, and replacing conditionals with polymorphism, all done safely with tests.