Naming, small methods and clear intent
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite works, but a new teammate opens calc(l, t) and cannot tell what it does. How do you write code that explains itself, so every change in this module is easy and safe?
Names that reveal intent
An intent-revealing name tells the reader why something exists and how it is used, so no comment is needed: countActiveProductsWithStockAbove instead of calc.
Example 1 runs the same rule twice: once with names like l, t and x, and once with names that tell the story.
Example 1 · calc(l, t) vs a name that tells the story
import java.util.List;
public class NamingDemo { // ---- Before: what do l, t, x and the 1 mean? ---- static int calc(List<int[]> l, int t) { int x = 0; for (int[] a : l) { if (a[1] == 1 && a[2] > t) { x++; } } return x; }
// ---- After: the same logic, names that tell the story ---- record Product(String sku, boolean isActive, int stock) { }
static int countActiveProductsWithStockAbove(List<Product> products, int minimumStock) { int count = 0; for (Product product : products) { if (product.isActive() && product.stock() > minimumStock) { count++; } } return count; }
public static void main(String[] args) { List<int[]> rows = List.of(new int[] {1, 1, 40}, new int[] {3, 1, 8}, new int[] {7, 0, 55}); System.out.println("Before: " + calc(rows, 10));
List<Product> products = List.of( new Product("MOB-RN13", true, 40), new Product("MOB-IP15", true, 8), new Product("ACC-OLD1", false, 55)); System.out.println("After: " + countActiveProductsWithStockAbove(products, 10)); }}Before: 1 After: 1
What this code does
- Both methods give the same answer. In the first, you must work out that
a[1] == 1means "active" anda[2]is stock; in the second, the names say so. - A record with named components (
isActive,stock) replaces the anonymousint[], so the call site reads like the rule: active products with stock above 10.
Avoid abbreviations (qty, cst, chk) and noise words that add length but no meaning: data, info, manager, obj, temp.
Methods are verbs (placeOrder, isLowStock), classes and variables are nouns (OrderService, deliveryCharge), and booleans read as questions (isActive, hasDigit).
getDataFromDatabaseAndReturnIt is long and still hides what the data is. Name the result, not the steps.Small methods that do one thing
Level of detail is how close a line is to the business story or to the mechanics: printHeader(id) is story, a loop that adds BigDecimal values is mechanics. A method keeps to one level.
printInvoice should read like a table of contents. Example 2 keeps it to five lines and moves the arithmetic one level down.
Example 2 · An invoice made of small methods
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.List;
record Line(String name, int quantity, BigDecimal unitPrice) { BigDecimal total() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }}
public class SmallMethodsDemo { // One method, one job at one level: it reads like a table of contents. static void printInvoice(int orderId, List<Line> lines) { printHeader(orderId); lines.forEach(SmallMethodsDemo::printLine); BigDecimal total = total(lines); printTotals(total, gstIncludedIn(total)); }
static void printHeader(int orderId) { System.out.println("Invoice for order " + orderId); }
static void printLine(Line line) { System.out.printf(" %-18s %d x %8s = %9s%n", line.name(), line.quantity(), line.unitPrice(), line.total()); }
static BigDecimal total(List<Line> lines) { return lines.stream().map(Line::total).reduce(BigDecimal.ZERO, BigDecimal::add); }
/** Prices already include 18% GST, so the GST part is total x 18 / 118. */ static BigDecimal gstIncludedIn(BigDecimal total) { return total.multiply(BigDecimal.valueOf(18)).divide(BigDecimal.valueOf(118), 2, RoundingMode.HALF_UP); }
static void printTotals(BigDecimal total, BigDecimal gst) { System.out.printf(" %-33s %9s%n", "Total", total); System.out.printf(" %-33s %9s%n", "of which GST 18%", gst); }
public static void main(String[] args) { printInvoice(17, List.of( new Line("Clean Code", 1, new BigDecimal("499.00")), new Line("boAt Airdopes 141", 2, new BigDecimal("1299.00")))); }}Invoice for order 17 Clean Code 1 x 499.00 = 499.00 boAt Airdopes 141 2 x 1299.00 = 2598.00 Total 3097.00 of which GST 18% 472.42
What this code does
printInvoicehas five lines, all at the "what happens" level; the "how" lives intotal,gstIncludedInand the print methods.- Each small method can be tested and reused on its own:
gstIncludedIn(new BigDecimal("3097.00"))is easy to check by hand (3097 × 18 / 118 = 472.42).
A good test: can you describe the method in one sentence without "and"? If not, extract the parts into methods with good names.
Long methods are not wrong because of their length. They are hard because a reader must hold many details in their head at once.
Guard clauses instead of deep nesting
A guard clause is an early return or throw at the top of a method for a case it cannot handle, so the main path below needs no else and no extra indentation.
Example 3 cancels an order. The nested version hides the real answer three levels deep; the guard version handles the odd cases first.
Example 3 · Cancelling an order: nested ifs vs guard clauses
public class GuardClauseDemo { enum Status { PLACED, SHIPPED, DELIVERED, CANCELLED }
record Order(int id, int customerId, Status status) { }
// ---- Before: the real answer hides three levels deep ---- static String cancelNested(Order order, int customerId) { String result; if (order != null) { if (order.customerId() == customerId) { if (order.status() == Status.PLACED) { result = "Order " + order.id() + " cancelled"; } else { result = "Order " + order.id() + " is " + order.status() + " and can no longer be cancelled"; } } else { result = "Order not found"; } } else { result = "Order not found"; } return result; }
// ---- After: handle the odd cases first and leave; the happy path is the last line ---- static String cancel(Order order, int customerId) { if (order == null || order.customerId() != customerId) { return "Order not found"; } if (order.status() != Status.PLACED) { return "Order " + order.id() + " is " + order.status() + " and can no longer be cancelled"; } return "Order " + order.id() + " cancelled"; }
public static void main(String[] args) { Order placed = new Order(16, 7, Status.PLACED); Order shipped = new Order(14, 2, Status.SHIPPED); Object[][] cases = {{placed, 7}, {shipped, 2}, {placed, 2}, {null, 7}}; for (Object[] c : cases) { Order order = (Order) c[0]; int customer = (Integer) c[1]; String before = cancelNested(order, customer); String after = cancel(order, customer); System.out.println(after + (before.equals(after) ? " (same as before)" : " (DIFFERENT)")); } }}Order 16 cancelled (same as before) Order 14 is SHIPPED and can no longer be cancelled (same as before) Order not found (same as before) Order not found (same as before)
What this code does
- The guard version answers the odd cases first (missing order, someone else's order, wrong status) and ends with the normal result, with no
elseat all. - The program runs both versions on four cases and prints whether they agree, a quick way to check a clean-up did not change behaviour.
Deeply nested if/else pushes the real work to the right and puts each else far from its if. With guards, every special case takes two or three lines, and the last line is the normal result.
In ShopLite's services, guards usually throw a meaningful exception such as ResourceNotFoundException.
Predict the output
Which guard answers first?
Follow the method from the top. The first guard that matches ends it.
Round 1 of 3
What does stockText(0) return?
Comments that explain why, not what
A why-comment explains what the code cannot say: why a rule exists, where it comes from or what trap to avoid. A comment that only repeats the code is noise.
Example 4 shows a comment that repeats the code, one that has gone out of date, and one that explains why.
Example 4 · Comments that repeat the code vs one that explains why
import java.math.BigDecimal;import java.math.RoundingMode;
public class CommentsDemo { static BigDecimal refundBefore(BigDecimal paid, int daysSinceDelivery) { // check if days is less than 7 if (daysSinceDelivery <= 10) { // multiply paid by 0.95 return paid.multiply(new BigDecimal("0.95")).setScale(2, RoundingMode.HALF_UP); } return BigDecimal.ZERO.setScale(2); }
static final int RETURN_WINDOW_DAYS = 10; static final BigDecimal REFUND_SHARE = new BigDecimal("0.95");
static BigDecimal refundAmount(BigDecimal paid, int daysSinceDelivery) { if (daysSinceDelivery > RETURN_WINDOW_DAYS) { return BigDecimal.ZERO.setScale(2); } // The courier charges us for the return trip, so we refund 95% (return policy, section 4.2). return paid.multiply(REFUND_SHARE).setScale(2, RoundingMode.HALF_UP); }
public static void main(String[] args) { BigDecimal paid = new BigDecimal("1299.00"); for (int days : new int[] {3, 10, 11}) { System.out.println("Day " + days + ": refund Rs " + refundAmount(paid, days) + " (before: Rs " + refundBefore(paid, days) + ")"); } }}Day 3: refund Rs 1234.05 (before: Rs 1234.05) Day 10: refund Rs 1234.05 (before: Rs 1234.05) Day 11: refund Rs 0.00 (before: Rs 0.00)
What this code does
- In
refundBefore, the comment "less than 7" is wrong: the code allows 10 days. Comments that describe the code drift away from it, and readers trust the wrong one. - In
refundAmount, constants and the method name say what happens; the single comment says why 95% and where the rule is written.
Comments that repeat code also go out of date, because nobody compiles them.
When you feel the need to explain what a block does, extract it into a method with that name instead. Keep a comment for the why: "the courier charges us for the return trip, so we refund 95%".
Magic numbers to named constants
A magic number is a literal value in code whose meaning is not obvious, such as 499 or "79". A named constant (static final) gives it a name and one place to change.
Example 5 works out delivery charges. Before: bare 499, "79" and 40. After: every rule has a name.
Example 5 · Delivery charges with named constants
import java.math.BigDecimal;
public class ConstantsDemo { // ---- Before ---- static BigDecimal deliveryBefore(BigDecimal subtotal, String pincode) { if (subtotal.compareTo(new BigDecimal("499")) >= 0) { return BigDecimal.ZERO.setScale(2); } if (pincode.startsWith("79")) { return new BigDecimal("90.00"); } return new BigDecimal("40.00"); }
// ---- After: every rule has a name, and changing it means changing one line ---- static final BigDecimal FREE_DELIVERY_FROM = new BigDecimal("499"); static final BigDecimal STANDARD_DELIVERY = new BigDecimal("40.00"); static final BigDecimal REMOTE_AREA_DELIVERY = new BigDecimal("90.00"); static final String REMOTE_AREA_PIN_PREFIX = "79"; // north-east India: longer courier routes
static BigDecimal deliveryCharge(BigDecimal subtotal, String pincode) { if (subtotal.compareTo(FREE_DELIVERY_FROM) >= 0) { return BigDecimal.ZERO.setScale(2); } if (pincode.startsWith(REMOTE_AREA_PIN_PREFIX)) { return REMOTE_AREA_DELIVERY; } return STANDARD_DELIVERY; }
public static void main(String[] args) { String[][] orders = {{"299.00", "560038"}, {"299.00", "793001"}, {"499.00", "793001"}}; for (String[] o : orders) { BigDecimal subtotal = new BigDecimal(o[0]); System.out.println("Rs " + o[0] + " to " + o[1] + ": delivery Rs " + deliveryCharge(subtotal, o[1]) + " (before: Rs " + deliveryBefore(subtotal, o[1]) + ")"); } }}Rs 299.00 to 560038: delivery Rs 40.00 (before: Rs 40.00) Rs 299.00 to 793001: delivery Rs 90.00 (before: Rs 90.00) Rs 499.00 to 793001: delivery Rs 0.00 (before: Rs 0.00)
What this code does
FREE_DELIVERY_FROM,STANDARD_DELIVERYandREMOTE_AREA_PIN_PREFIXturn three unexplained values into business rules you can read and change in one place.- Money stays
BigDecimal, and the constants are created from strings ("40.00") so the values are exact.
When the shop raises the free-delivery limit to Rs 599, you change one line instead of searching for every 499, some of which may mean something else.
In a Spring Boot app, values that change per environment, such as a page size, go one step further into configuration properties.
Find the bug
Tap the unclear line
Each snippet has one line that hides its meaning. Tap it, then read the fix.
Tap the comment that only repeats the code.
Round 1 of 3Next step
Check your understanding
12 quick questions