Review and improve an existing design
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.
ShopLite's old OrderManager works and its demo totals are correct, but nobody dares to change it. This checkpoint reviews how to read such code, write review comments that get acted on, and refactor without changing behaviour.
A code-review checklist: SOLID, coupling, naming, pattern fit
A review checklist is a short list of questions you ask of every class, so reviews are consistent and nothing obvious is missed.
Four groups cover most design problems: the SOLID principles, coupling (how much one class depends on the details of another), naming and pattern fit (a pattern used where it helps, and nowhere else).
SOLID S Does the class have one reason to change? O Does a new payment or offer mean editing this class? L Can every subclass stand in for its parent? I Do classes depend on methods they never use? D Does it create its own dependencies with new, or receive them?Coupling Hard-wired classes, static mutable state, string type codes?Naming Can a new teammate guess what proc, t, r, d mean?Money double for rupees? magic numbers like 499 and 40?Patterns Is a pattern solving a stated need, or just decoration?Tests Can this be tested without sending a real email?Go through the list once per class, note each problem with the line it is on, and only then think about fixes. Reviewing and redesigning at the same time makes you miss things.
Reviewing a supplied ShopLite module with real flaws
The old ShopLite OrderManager has one method, proc, that prices an order, applies a coupon, adds shipping, takes payment, sends an email and logs the order. It works, and the demo shows correct totals.
Example 1 · The module under review
import java.util.ArrayList;import java.util.List;
class EmailSender { void send(String to, String body) { System.out.println(" email to " + to + ": " + body); }}
class OrderManager { static List<String> log = new ArrayList<>(); // shared, mutable, static
String proc(String cust, double[] p, int[] q, String pay, String code) { double t = 0; for (int i = 0; i < p.length; i++) t += p[i] * q[i]; if (code != null && code.equals("SAVE10")) t = t - t * 0.10; if (t < 499) t = t + 40; // magic numbers String r; if (pay.equals("UPI")) r = "UPI collect from " + cust; else if (pay.equals("CARD")) r = "Card charged for " + cust; else r = "Unknown payment"; EmailSender s = new EmailSender(); // hard-wired dependency s.send(cust, "Order total " + String.format("%.2f", t)); log.add(cust + ":" + String.format("%.2f", t)); return r + ", total " + String.format("%.2f", t); }}
public class OrderManagerDemo { public static void main(String[] args) { OrderManager m = new OrderManager(); System.out.println(m.proc("asha@mail.in", new double[] {399, 249}, new int[] {1, 2}, "UPI", "SAVE10")); System.out.println(m.proc("ravi@mail.in", new double[] {120}, new int[] {3}, "CARD", null)); System.out.println(m.proc("meera@mail.in", new double[] {99.9}, new int[] {5}, "WALLET", null)); System.out.println("Log: " + OrderManager.log); }}email to asha@mail.in: Order total 807.30 UPI collect from asha@mail.in, total 807.30 email to ravi@mail.in: Order total 400.00 Card charged for ravi@mail.in, total 400.00 email to meera@mail.in: Order total 499.50 Unknown payment, total 499.50 Log: [asha@mail.in:807.30, ravi@mail.in:400.00, meera@mail.in:499.50]
What this code does
- The output is correct, which is why code like this survives for years. The problems are in how hard it is to change and test.
- One method prices, pays, emails and logs; payment types are strings;
EmailSenderis created inside, so every run sends "real" email. logisstatic, so everyOrderManagerin the program writes to the same list, and nothing ever clears it.
Run the checklist against it. Single responsibility: five jobs in one method. Open/closed: every payment type is an if on a string. Dependency inversion: it creates EmailSender itself, so a test sends real emails. Plus double money, magic numbers, a static mutable log shared by every instance, and names like t, p, q and r.
Find the bug
Find the flaw
Each snippet is from the old OrderManager. Tap the line that a review should flag.
How the email is sent.
Round 1 of 3Writing review comments that explain why
A review comment should say what the problem is, why it matters in this codebase, and what to do instead.
"Bad naming" teaches nothing; "t is the order total and is used 6 times; total would save every reader a lookup" is specific and easy to act on.
[must] proc() line 4: total uses double. 0.1 is not exact in binary, so paise drift on some carts. Use BigDecimal built from strings.[must] proc() line 12: new EmailSender() inside the method. Tests send real mail and we cannot switch to SMS. Pass a NotificationService in.[should] proc() lines 8-11: if-chain on payment strings. Each new method edits this class. A Map<String, PaymentMethod> keeps it closed.[should] static log: shared by every OrderManager, grows forever, not thread-safe. Make it an instance field or a separate OrderLog.[nit] names t, p, q, r, s: rename to total, prices, quantities...Label how important each comment is, so the author knows what must change before merging and what is a suggestion. Comment on the code, never on the person, and keep each comment about one thing.
Applying the improvements and comparing before/after
A behaviour-preserving refactor changes the structure of code but not what it does: same inputs, same outputs, same messages.
Prove it with a before/after comparison (also called a characterization or golden-master test): run the old and new code on the same set of orders and check that every output matches.
Example 2 · After the review: one job per class
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.ArrayList;import java.util.List;import java.util.Map;
record OrderLine(BigDecimal price, int qty) { BigDecimal total() { return price.multiply(BigDecimal.valueOf(qty)); }}
interface PaymentMethod { String charge(String customer); }
class UpiPayment implements PaymentMethod { public String charge(String customer) { return "UPI collect from " + customer; }}
class CardPayment implements PaymentMethod { public String charge(String customer) { return "Card charged for " + customer; }}
interface NotificationService { void send(String to, String body); }
class EmailNotificationService implements NotificationService { public void send(String to, String body) { System.out.println(" email to " + to + ": " + body); }}
class OrderPricing { static final BigDecimal FREE_SHIPPING_FROM = new BigDecimal("499"); static final BigDecimal SHIPPING_FEE = new BigDecimal("40"); static final BigDecimal SAVE10_RATE = new BigDecimal("0.10");
BigDecimal total(List<OrderLine> lines, String couponCode) { BigDecimal total = lines.stream().map(OrderLine::total).reduce(BigDecimal.ZERO, BigDecimal::add); if ("SAVE10".equals(couponCode)) total = total.subtract(total.multiply(SAVE10_RATE)); if (total.compareTo(FREE_SHIPPING_FROM) < 0) total = total.add(SHIPPING_FEE); return total.setScale(2, RoundingMode.HALF_UP); }}
class CheckoutService { private final OrderPricing pricing; private final Map<String, PaymentMethod> paymentMethods; private final NotificationService notifier; private final List<String> orderLog = new ArrayList<>();
CheckoutService(OrderPricing pricing, Map<String, PaymentMethod> paymentMethods, NotificationService notifier) { this.pricing = pricing; this.paymentMethods = paymentMethods; this.notifier = notifier; }
String checkout(String customer, List<OrderLine> lines, String paymentType, String couponCode) { BigDecimal total = pricing.total(lines, couponCode); PaymentMethod method = paymentMethods.get(paymentType); String paymentResult = method == null ? "Unknown payment" : method.charge(customer); notifier.send(customer, "Order total " + total); orderLog.add(customer + ":" + total); return paymentResult + ", total " + total; }}
public class CheckoutServiceDemo { public static void main(String[] args) { CheckoutService service = new CheckoutService(new OrderPricing(), Map.of("UPI", new UpiPayment(), "CARD", new CardPayment()), new EmailNotificationService());
System.out.println(service.checkout("asha@mail.in", List.of(new OrderLine(new BigDecimal("399"), 1), new OrderLine(new BigDecimal("249"), 2)), "UPI", "SAVE10")); System.out.println(service.checkout("ravi@mail.in", List.of(new OrderLine(new BigDecimal("120"), 3)), "CARD", null)); System.out.println(service.checkout("meera@mail.in", List.of(new OrderLine(new BigDecimal("99.9"), 5)), "WALLET", null)); }}email to asha@mail.in: Order total 807.30 UPI collect from asha@mail.in, total 807.30 email to ravi@mail.in: Order total 400.00 Card charged for ravi@mail.in, total 400.00 email to meera@mail.in: Order total 499.50 Unknown payment, total 499.50
What this code does
- Pricing, payment, notification and the service are separate; each has one reason to change, and the numbers 499, 40 and 0.10 have names.
- The service receives its payment methods and
NotificationServicein the constructor, so a test can pass a recording notifier and an SMS channel needs no edit here. - The printed lines match the old ones, including a real bug: the unknown
WALLETpayment still gets an "Order total" email. The refactor keeps it on purpose; fixing it is a separate, named change.
Example 3 · Proving the behaviour did not change
import java.io.ByteArrayOutputStream;import java.io.PrintStream;import java.math.BigDecimal;import java.math.RoundingMode;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.function.Supplier;
class EmailSender { void send(String to, String body) { System.out.println(" email to " + to + ": " + body); }}
class OrderManager { static List<String> log = new ArrayList<>();
String proc(String cust, double[] p, int[] q, String pay, String code) { double t = 0; for (int i = 0; i < p.length; i++) t += p[i] * q[i]; if (code != null && code.equals("SAVE10")) t = t - t * 0.10; if (t < 499) t = t + 40; // magic numbers String r; if (pay.equals("UPI")) r = "UPI collect from " + cust; else if (pay.equals("CARD")) r = "Card charged for " + cust; else r = "Unknown payment"; EmailSender s = new EmailSender(); // hard-wired dependency s.send(cust, "Order total " + String.format("%.2f", t)); log.add(cust + ":" + String.format("%.2f", t)); return r + ", total " + String.format("%.2f", t); }}
record OrderLine(BigDecimal price, int qty) { BigDecimal total() { return price.multiply(BigDecimal.valueOf(qty)); }}
interface PaymentMethod { String charge(String customer); }
class UpiPayment implements PaymentMethod { public String charge(String customer) { return "UPI collect from " + customer; }}
class CardPayment implements PaymentMethod { public String charge(String customer) { return "Card charged for " + customer; }}
interface NotificationService { void send(String to, String body); }
class EmailNotificationService implements NotificationService { public void send(String to, String body) { System.out.println(" email to " + to + ": " + body); }}
class OrderPricing { static final BigDecimal FREE_SHIPPING_FROM = new BigDecimal("499"); static final BigDecimal SHIPPING_FEE = new BigDecimal("40"); static final BigDecimal SAVE10_RATE = new BigDecimal("0.10");
BigDecimal total(List<OrderLine> lines, String couponCode) { BigDecimal total = lines.stream().map(OrderLine::total).reduce(BigDecimal.ZERO, BigDecimal::add); if ("SAVE10".equals(couponCode)) total = total.subtract(total.multiply(SAVE10_RATE)); if (total.compareTo(FREE_SHIPPING_FROM) < 0) total = total.add(SHIPPING_FEE); return total.setScale(2, RoundingMode.HALF_UP); }}
class CheckoutService { private final OrderPricing pricing; private final Map<String, PaymentMethod> paymentMethods; private final NotificationService notifier; private final List<String> orderLog = new ArrayList<>();
CheckoutService(OrderPricing pricing, Map<String, PaymentMethod> paymentMethods, NotificationService notifier) { this.pricing = pricing; this.paymentMethods = paymentMethods; this.notifier = notifier; }
String checkout(String customer, List<OrderLine> lines, String paymentType, String couponCode) { BigDecimal total = pricing.total(lines, couponCode); PaymentMethod method = paymentMethods.get(paymentType); String paymentResult = method == null ? "Unknown payment" : method.charge(customer); notifier.send(customer, "Order total " + total); orderLog.add(customer + ":" + total); return paymentResult + ", total " + total; }}
public class BeforeAfterDemo { // run code and collect everything it prints plus what it returns static String capture(Supplier<String> run) { PrintStream original = System.out; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(buffer, true)); try { System.out.println(run.get()); } finally { System.setOut(original); } return buffer.toString(); }
public static void main(String[] args) { OrderManager before = new OrderManager(); CheckoutService after = new CheckoutService(new OrderPricing(), Map.of("UPI", new UpiPayment(), "CARD", new CardPayment()), new EmailNotificationService());
double[][] prices = {{399, 249}, {120}, {99.9}, {554.5}, {150}}; int[][] qtys = {{1, 2}, {3}, {5}, {1}, {3}}; String[] pays = {"UPI", "CARD", "WALLET", "UPI", "CARD"}; String[] coupons = {"SAVE10", null, null, "SAVE10", "SAVE10"};
int same = 0; for (int i = 0; i < prices.length; i++) { int k = i; List<OrderLine> lines = new ArrayList<>(); for (int j = 0; j < prices[k].length; j++) lines.add(new OrderLine(BigDecimal.valueOf(prices[k][j]), qtys[k][j])); String old = capture(() -> before.proc("c" + k, prices[k], qtys[k], pays[k], coupons[k])); String now = capture(() -> after.checkout("c" + k, lines, pays[k], coupons[k])); boolean match = old.equals(now); if (match) same++; System.out.println("Order " + (k + 1) + " (" + pays[k] + ", " + coupons[k] + "): " + (match ? "same" : "DIFFERENT")); } System.out.println(same + " of " + prices.length + " orders behave the same"); }}Order 1 (UPI, SAVE10): same Order 2 (CARD, null): same Order 3 (WALLET, null): same Order 4 (UPI, SAVE10): same Order 5 (CARD, SAVE10): same 5 of 5 orders behave the same
What this code does
captureswapsSystem.outfor a buffer, so the email line and the returned text of each version can be compared as plain strings.- The cases include an unknown payment type and totals near the Rs 499 line (Rs 554.50 with 10% off is Rs 499.05, just above it), where a refactor most easily changes behaviour.
- Run this after every small refactoring step. If one order says
DIFFERENT, the last step changed behaviour and is easy to find.
Make the comparison first, then refactor in small steps and re-run it after each one. Include the awkward cases (no coupon, unknown payment type, totals near the free-shipping line), because that is where a refactor quietly changes behaviour.
Fix the error
Keep the behaviour
The refactor changed a result. Pick the line that restores the old behaviour.
Round 1 of 2
Old code: a total of Rs 499 or more ships free.
Error
Wrong result: a Rs 499.00 cart now pays Rs 40 shipping
Finish up
Mark complete & continue
Next: Design patterns section review