Code smells: duplication, long methods, god classes
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A class that works today can still make tomorrow's change expensive: one fix needs five edits and one of them is forgotten. How do you spot that trouble in ShopLite's code before you touch it?
Code smells, and the first one: duplicated code
A code smell is a surface sign in code that usually points to a deeper design problem. Smelly code still works today; the trouble comes on the day it must change.
Example 1 is a copy-paste bug: a rounding fix reached one copy of the price rule but not the other.
Example 1 · A copy-paste bug: two prices for one product
import java.math.BigDecimal;import java.math.RoundingMode;
public class DuplicationBugDemo { // Copy 1, used by the mobile app. Last month someone fixed the rounding here... static BigDecimal appPrice(BigDecimal price, int discountPercent) { BigDecimal off = price.multiply(BigDecimal.valueOf(discountPercent)) .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP); return price.subtract(off); }
// Copy 2, used by the website: the same rule, pasted earlier, never fixed. static BigDecimal webPrice(BigDecimal price, int discountPercent) { BigDecimal off = price.multiply(BigDecimal.valueOf(discountPercent)) .divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN); return price.subtract(off); }
// The fix for the smell: ONE method that both callers use. static BigDecimal discountedPrice(BigDecimal price, int discountPercent) { BigDecimal off = price.multiply(BigDecimal.valueOf(discountPercent)) .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP); return price.subtract(off); }
public static void main(String[] args) { BigDecimal backpack = new BigDecimal("449.90"); System.out.println("App: Rs " + appPrice(backpack, 15)); System.out.println("Website: Rs " + webPrice(backpack, 15)); System.out.println("One rule for both: Rs " + discountedPrice(backpack, 15)); }}App: Rs 382.41 Website: Rs 382.42 One rule for both: Rs 382.41
What this code does
- The two copies differ only in the rounding mode, after a fix reached one copy but not the other. The app and the website now show different prices.
- With one
discountedPricemethod, the next fix happens once and every caller gets it.
Duplicated code is the same logic written in more than one place, usually by copy and paste. It looks harmless until the rule changes: someone fixes one copy, and the others stay wrong. Keep each rule in one place, a method or a class, and call it from everywhere.
Be careful with code that only looks similar: if two pieces change for different reasons, they are not real duplicates.
Predict the output
Two copies, two answers
The discount on Rs 449.90 at 15% is 67.485. Work out what each copy does with it.
Round 1 of 2
What discount does each copy subtract?
Long methods and long parameter lists
A parameter object is a record or class that groups values that travel together, so one named object replaces a long list of parameters.
Example 2 calls a method with six parameters, three of them int. Two values swap places and the code still compiles.
Example 2 · A long parameter list lets two ints swap silently
import java.math.BigDecimal;
public class LongParameterListDemo { static String createProduct(String sku, String name, int categoryId, BigDecimal price, int stock, boolean active) { return sku + " '" + name + "' in category " + categoryId + ", Rs " + price + ", stock " + stock + (active ? "" : " (inactive)"); }
record NewProduct(String sku, String name, int categoryId, BigDecimal price, int stock, boolean active) { NewProduct { if (stock < 0) { throw new IllegalArgumentException("stock must be 0 or more"); } } }
static String createProduct(NewProduct p) { return createProduct(p.sku(), p.name(), p.categoryId(), p.price(), p.stock(), p.active()); }
public static void main(String[] args) { // Compiles fine, but stock (30) and category (4) are swapped: System.out.println(createProduct("ACC-KB100", "Zebronics Wireless Keyboard", 30, new BigDecimal("999.00"), 4, true));
NewProduct keyboard = new NewProduct("ACC-KB100", "Zebronics Wireless Keyboard", 4, new BigDecimal("999.00"), 30, true); System.out.println(createProduct(keyboard)); }}ACC-KB100 'Zebronics Wireless Keyboard' in category 30, Rs 999.00, stock 4 ACC-KB100 'Zebronics Wireless Keyboard' in category 4, Rs 999.00, stock 30
What this code does
- The first call compiles and runs, but the keyboard lands in category 30 with stock 4. Nothing in the call shows which
intis which. NewProductgroups the six values, checks its own rule (stock not negative) and travels through the code as one named object.
A long method does many things at many levels of detail, so you must read all of it to change any of it. A long parameter list (more than three or four parameters) is hard to call correctly: with createProduct(sku, name, 30, price, 4, true), swapping two int values still compiles.
Split long methods with extract method. Replace long lists with a record such as NewProduct, so every value has a name and the rules about the values live in one place.
God classes that know everything
A god class is a class that does far too much: products, orders, payments, e-mails and reports in one ShopLiteManager. It has many reasons to change.
Example 3 builds a whole ShopLiteManager just to check one delivery rule, then checks the same rule in a class with one job.
Example 3 · A god class vs a class with one job
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;
class ShopLiteManager { final List<String> log = new ArrayList<>();
ShopLiteManager(String dbUrl, String smtpHost, String upiKey, String smsKey) { log.add("connected to " + dbUrl); log.add("mail server " + smtpHost); log.add("UPI key " + upiKey.substring(0, 3) + "..."); log.add("SMS key " + smsKey.substring(0, 3) + "..."); }
BigDecimal deliveryCharge(BigDecimal itemsTotal) { return itemsTotal.compareTo(new BigDecimal("499")) >= 0 ? new BigDecimal("0.00") : new BigDecimal("40.00"); }
void createProduct(String sku) { log.add("product " + sku); } void placeOrder(int customerId) { log.add("order for " + customerId); } void chargeUpi(int orderId) { log.add("UPI for " + orderId); } void sendInvoiceEmail(int orderId) { log.add("mail " + orderId); } void sendOtpSms(String phone) { log.add("sms"); } String salesReport() { return "report"; }}
class DeliveryPricing { static final BigDecimal FREE_DELIVERY_FROM = new BigDecimal("499");
BigDecimal deliveryCharge(BigDecimal itemsTotal) { return itemsTotal.compareTo(FREE_DELIVERY_FROM) >= 0 ? new BigDecimal("0.00") : new BigDecimal("40.00"); }}
public class GodClassDemo { public static void main(String[] args) { // To check ONE pricing rule, we must build the whole shop: ShopLiteManager manager = new ShopLiteManager("jdbc:mysql://localhost/shoplite", "smtp.example.com", "upi-test-key", "sms-test-key"); System.out.println("God class: Rs " + manager.deliveryCharge(new BigDecimal("299.00"))); System.out.println(" setup it needed: " + manager.log);
DeliveryPricing pricing = new DeliveryPricing(); System.out.println("Small class: Rs " + pricing.deliveryCharge(new BigDecimal("299.00"))); System.out.println(" setup it needed: nothing"); }}God class: Rs 40.00 setup it needed: [connected to jdbc:mysql://localhost/shoplite, mail server smtp.example.com, UPI key upi..., SMS key sms...] Small class: Rs 40.00 setup it needed: nothing
What this code does
- To check one delivery rule,
ShopLiteManagerneeded a database URL, a mail server and two API keys, because its constructor serves every job it has: pricing, products, orders, payments, e-mail, SMS and reports. DeliveryPricinghas one reason to change (the delivery rule) and needs nothing to be created, so it is trivial to test and reuse.
Every change to a god class risks breaking something unrelated, and testing one small rule means building everything the class needs.
The cure is the single responsibility principle: a class should have one reason to change. Split by job, as ShopLite's packages already do: ProductService, OrderService, PaymentService, each with only the dependencies its job needs.
Primitive obsession and feature envy
Primitive obsession is using plain String, int or double for ideas that have rules, such as a phone number, a pincode or money, so the rule is repeated wherever the value is used.
Example 4 replaces a plain String phone number with a Phone record, and moves an order total from a printer into Order.
Example 4 · A Phone value type and an order that adds itself up
import java.math.BigDecimal;import java.util.List;
record Phone(String digits) { Phone { if (digits == null || !digits.matches("[6-9][0-9]{9}")) { throw new IllegalArgumentException("Phone must be 10 digits starting with 6-9: " + digits); } }
String masked() { return "******" + digits.substring(6); }}
record OrderLine(String sku, int quantity, BigDecimal unitPrice) { BigDecimal total() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }}
record Order(int id, List<OrderLine> lines) { BigDecimal total() { return lines.stream().map(OrderLine::total).reduce(BigDecimal.ZERO, BigDecimal::add); }}
class ReceiptPrinter { // Smell (feature envy): this method only uses Order's data, and repeats Order's rule. String enviousLine(Order order) { BigDecimal sum = BigDecimal.ZERO; for (OrderLine l : order.lines()) { sum = sum.add(l.unitPrice().multiply(BigDecimal.valueOf(l.quantity()))); } return "Order " + order.id() + ": Rs " + sum; }
// Better: ask the order; the printer only prints. String line(Order order) { return "Order " + order.id() + ": Rs " + order.total(); }}
public class PrimitiveObsessionDemo { public static void main(String[] args) { Phone phone = new Phone("9876543201"); System.out.println("OTP to " + phone.masked()); try { new Phone("12345"); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); }
Order order = new Order(17, List.of( new OrderLine("BK-CLEAN", 1, new BigDecimal("499.00")), new OrderLine("ACC-AD141", 2, new BigDecimal("1299.00")))); ReceiptPrinter printer = new ReceiptPrinter(); System.out.println(printer.enviousLine(order)); System.out.println(printer.line(order)); }}OTP to ******3201 Rejected: Phone must be 10 digits starting with 6-9: 12345 Order 17: Rs 3097.00 Order 17: Rs 3097.00
What this code does
Phonechecks the rule once, in its compact constructor; aPhoneobject that exists is always valid, and masking lives next to the data it masks.enviousLinerepeats the order's arithmetic;lineasks the order. Same output, but now the total rule exists only inOrder.
A small value type, such as record Phone(String digits) that checks itself in its constructor, keeps the rule ("10 digits starting with 6 to 9") in one place.
Feature envy is a method that is more interested in another class's data than its own, for example a printer that adds up an order's lines itself. Move the logic to the class that owns the data (order.total()), and the envious method shrinks to one line.
Spotting smells in a ShopLite class
Example 5 is one ShopLite class with several smells at once. Count them before you read the answer.
Example 5 · OrderHelper: a class with six smells
import java.util.List;
/** A ShopLite class with several smells. It still runs, which is why smells survive. */class OrderHelper { String handle(int custId, String phone, String pin, String city, List<String> skus, List<Integer> qtys, List<Integer> prices, String coupon) { if (!phone.matches("[6-9][0-9]{9}")) { return "bad phone"; } int total = 0; for (int i = 0; i < skus.size(); i++) { total += prices.get(i) * qtys.get(i); } if (coupon != null && coupon.equals("FEST20") && total >= 999) { total -= 200; } int delivery = total >= 499 ? 0 : (pin.startsWith("79") ? 90 : 40); return "customer " + custId + " pays Rs " + (total + delivery) + " to " + city; }}
public class SmellSpottingDemo { public static void main(String[] args) { OrderHelper helper = new OrderHelper(); System.out.println(helper.handle(1, "9876543201", "560038", "Bengaluru", List.of("BK-CLEAN", "ACC-AD141"), List.of(1, 2), List.of(499, 1299), "FEST20")); System.out.println(helper.handle(2, "98765", "793001", "Shillong", List.of("BK-ATOMIC"), List.of(1), List.of(399), null)); }}customer 1 pays Rs 2897 to Bengaluru bad phone
What this code does
- The class works, so nothing fails. Count the smells: a vague name (
OrderHelper,handle), eight parameters with three parallel lists, plain strings for phone and pincode, a phone check that other classes repeat, magic numbers (999,200,499,"79") and money asint. - Each smell has a standard fix: rename, a request record,
PhoneandPincodevalue types, named constants andBigDecimal. Practice 6 does exactly that.
Smells rarely come alone. Read a class with this short list in mind and note each one before you change anything:
- Vague names:
Helper,Manager,Util,handle,process,doIt. - Many parameters, parallel lists (
skus,qtys,prices) or manyString/intparameters in a row. - Magic numbers, money as
intordouble, the same validation in several classes. - A method you cannot describe in one sentence, or a class with many unrelated dependencies.
Find the bug
Tap the smell
Each snippet comes from OrderHelper. Tap the line that shows the named smell.
Tap the line that checks a phone number held as a plain String.
Round 1 of 3Next step
Check your understanding
12 quick questions