Skip to lesson

Refactoring to patterns practice

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 messy code needs the right fix, and sometimes that fix removes a pattern. This optional checkpoint practises seeing the smell, picking the smallest fix and proving the output did not change.

Refactor a notification switch into strategies

ShopLite sends notifications with one switch on the channel name in send, costPaise and maxLength. The code below refactors it into strategies and checks for zero mismatches.

Example 1 · Notification switch → strategies, checked

NotificationRefactorDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
// BEFORE: the same switch in three methodsclass LegacyNotifier {    String send(String channel, String to, String text) {        switch (channel) {            case "SMS": return "SMS to " + to + ": " + text;            case "EMAIL": return "Email to " + to + ": " + text;            case "PUSH": return "Push to " + to + ": " + text;            default: throw new IllegalArgumentException("Unknown channel: " + channel);        }    }
    int costPaise(String channel) {        switch (channel) {            case "SMS": return 15;            case "EMAIL": return 0;            case "PUSH": return 2;            default: throw new IllegalArgumentException("Unknown channel: " + channel);        }    }
    int maxLength(String channel) {        switch (channel) {            case "SMS": return 160;            case "EMAIL": return 10000;            case "PUSH": return 240;            default: throw new IllegalArgumentException("Unknown channel: " + channel);        }    }}
// AFTER: one strategy per channel, one place that choosesinterface Channel {    String send(String to, String text);    int costPaise();    int maxLength();}
class SmsChannel implements Channel {    public String send(String to, String text) { return "SMS to " + to + ": " + text; }    public int costPaise() { return 15; }    public int maxLength() { return 160; }}
class EmailChannel implements Channel {    public String send(String to, String text) { return "Email to " + to + ": " + text; }    public int costPaise() { return 0; }    public int maxLength() { return 10000; }}
class PushChannel implements Channel {    public String send(String to, String text) { return "Push to " + to + ": " + text; }    public int costPaise() { return 2; }    public int maxLength() { return 240; }}
class Channels {    private final Map<String, Channel> byName = new LinkedHashMap<>();
    Channels() {        byName.put("SMS", new SmsChannel());        byName.put("EMAIL", new EmailChannel());        byName.put("PUSH", new PushChannel());    }
    Channel get(String name) {        Channel c = byName.get(name);        if (c == null) throw new IllegalArgumentException("Unknown channel: " + name);        return c;    }}
public class NotificationRefactorDemo {    public static void main(String[] args) {        LegacyNotifier old = new LegacyNotifier();        Channels channels = new Channels();        int mismatches = 0;        for (String name : List.of("SMS", "EMAIL", "PUSH")) {            Channel c = channels.get(name);            String sent = c.send("Riya", "ORD-11 shipped");            if (!sent.equals(old.send(name, "Riya", "ORD-11 shipped"))                    || c.costPaise() != old.costPaise(name) || c.maxLength() != old.maxLength(name)) {                mismatches++;            }            System.out.println(sent + " | " + c.costPaise() + " paise | max " + c.maxLength());        }        System.out.println("Mismatches with legacy: " + mismatches);    }}
Output
SMS to Riya: ORD-11 shipped | 15 paise | max 160
Email to Riya: ORD-11 shipped | 0 paise | max 10000
Push to Riya: ORD-11 shipped | 2 paise | max 240
Mismatches with legacy: 0

What this code does

  • Each channel class holds the three former switch arms for that channel; Channels.get is the only place that maps a name to an object.
  • The loop compares every method with the legacy class and reports zero mismatches before the old code is deleted.

The smell: the same switch in three methods, so adding WhatsApp means editing three places.

The fix: a Channel interface with one class per channel, each switch arm moved unchanged, and a single Channels registry that turns a name into an object. Keep the legacy class until the comparison shows zero mismatches.

Remove duplication from two export classes

A CSV export and a JSON-lines export loop, add totals and append lines in the same order. The code below moves the shared steps into one template method.

Example 2 · Two exports, one template

ExportDuplicationDemo.javaJava
import java.util.List;
record Sale(String product, int qty, int amount) { }
abstract class SalesExport {    final String export(List<Sale> sales) {        StringBuilder out = new StringBuilder(header()).append('\n');        int total = 0;        for (Sale s : sales) {            out.append(row(s)).append('\n');            total += s.amount();        }        out.append(totalLine(total));        return out.toString();    }
    abstract String header();    abstract String row(Sale s);    abstract String totalLine(int total);}
class CsvSalesExport extends SalesExport {    String header() { return "product,qty,amount"; }    String row(Sale s) { return s.product() + "," + s.qty() + "," + s.amount(); }    String totalLine(int total) { return "TOTAL,," + total; }}
class JsonLinesSalesExport extends SalesExport {    String header() { return "{\"report\":\"sales\"}"; }    String row(Sale s) {        return "{\"product\":\"" + s.product() + "\",\"qty\":" + s.qty() + ",\"amount\":" + s.amount() + "}";    }    String totalLine(int total) { return "{\"total\":" + total + "}"; }}
public class ExportDuplicationDemo {    public static void main(String[] args) {        List<Sale> sales = List.of(new Sale("Earbuds", 2, 2998), new Sale("Notebook", 5, 300));        System.out.println(new CsvSalesExport().export(sales));        System.out.println(new JsonLinesSalesExport().export(sales));    }}
Output
product,qty,amount
Earbuds,2,2998
Notebook,5,300
TOTAL,,3298
{"report":"sales"}
{"product":"Earbuds","qty":2,"amount":2998}
{"product":"Notebook","qty":5,"amount":300}
{"total":3298}

What this code does

  • SalesExport.export holds the loop, the running total and the line breaks once.
  • The CSV and JSON-lines classes now hold only their formats, three short methods each.

The smell: only the header, row and total formats differ between the two classes.

The fix: an abstract SalesExport with a final export method holding the loop and the total, and three abstract steps. A new format is now one small subclass. If only one step differed, a lambda parameter would be lighter.

Undo an unnecessary pattern

ShopLite formats rupees, its only currency, through four types. The code below collapses them into one static method and checks the output is the same.

Example 3 · Four types collapsed into one method

UndoPatternDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;
// BEFORE (shown as comments): CurrencyFormatStrategy, RupeeFormatStrategy,// CurrencyFormatStrategyFactory and a singleton holder, for the one currency ShopLite uses.
// AFTER: one small class with one methodclass Money {    static String rupees(BigDecimal amount) {        return "Rs. " + amount.setScale(2, RoundingMode.HALF_UP);    }}
public class UndoPatternDemo {    public static void main(String[] args) {        System.out.println(Money.rupees(new BigDecimal("1499")));        System.out.println(Money.rupees(new BigDecimal("59.995")));    }}
Output
Rs. 1499.00
Rs. 60.00

What this code does

  • The comment lists what was removed: a strategy interface, its only implementation, a factory and a singleton holder.
  • Money.rupees gives the same output with setScale(2, RoundingMode.HALF_UP), so 59.995 prints as Rs. 60.00.

The smell: a strategy interface, one implementation, a factory and a singleton holder, all to format rupees. Nothing varies and no test needs a fake.

The fix: one static method. Remove the layers one at a time and check the output after each. If a second currency ever arrives, refactor back to Strategy then, with real knowledge of what varies.

Name the wrapper pattern

Four OrderRepository wrappers appear below. Name each one with the three checks, then compare your answers with the output.

Example 4 · Four OrderRepository wrappers

NameTheWrapperDemo.javaJava
import java.util.HashMap;import java.util.List;import java.util.Map;
interface OrderRepository {    String findStatus(String orderId);}
class DbOrderRepository implements OrderRepository {    public String findStatus(String orderId) {        System.out.println("    (db query " + orderId + ")");        return orderId.equals("ORD-1") ? "SHIPPED" : "PLACED";    }}
class CachingOrderRepository implements OrderRepository {    private final OrderRepository real;    private final Map<String, String> cache = new HashMap<>();    CachingOrderRepository(OrderRepository real) { this.real = real; }    public String findStatus(String id) { return cache.computeIfAbsent(id, real::findStatus); }}
class AuditingOrderRepository implements OrderRepository {    private final OrderRepository inner;    AuditingOrderRepository(OrderRepository inner) { this.inner = inner; }    public String findStatus(String id) {        String status = inner.findStatus(id);        System.out.println("    [audit] status of " + id + " read");        return status;    }}
class LegacyOrderDao {    int statusCode(long orderNumber) { return orderNumber == 1 ? 3 : 1; }}
class LegacyOrderAdapter implements OrderRepository {    private final LegacyOrderDao dao = new LegacyOrderDao();    public String findStatus(String id) {        int code = dao.statusCode(Long.parseLong(id.substring(4)));        return List.of("?", "PLACED", "PAID", "SHIPPED").get(code);    }}
class OrderTrackingFacade {    private final OrderRepository orders;    OrderTrackingFacade(OrderRepository orders) { this.orders = orders; }    String track(String id) {        String status = orders.findStatus(id);        String eta = status.equals("SHIPPED") ? "arrives in 2 days" : "not shipped yet";        return id + ": " + status + ", " + eta;    }}
public class NameTheWrapperDemo {    public static void main(String[] args) {        OrderRepository a = new CachingOrderRepository(new DbOrderRepository());        System.out.println("A (Proxy): " + a.findStatus("ORD-1") + ", again " + a.findStatus("ORD-1"));        OrderRepository b = new AuditingOrderRepository(new DbOrderRepository());        System.out.println("B (Decorator): " + b.findStatus("ORD-2"));        System.out.println("C (Adapter): " + new LegacyOrderAdapter().findStatus("ORD-1"));        System.out.println("D (Facade): " + new OrderTrackingFacade(new LegacyOrderAdapter()).track("ORD-1"));    }}
Output
    (db query ORD-1)
A (Proxy): SHIPPED, again SHIPPED
    (db query ORD-2)
    [audit] status of ORD-2 read
B (Decorator): PLACED
C (Adapter): SHIPPED
D (Facade): ORD-1: SHIPPED, arrives in 2 days

What this code does

  • A queries the database once and then answers from its cache (Proxy). B always calls through and adds an audit line (Decorator).
  • C turns a legacy long-and-code API into findStatus (Adapter). D offers one track method that combines a lookup and an ETA rule (Facade).

Use the three checks: a different interface inside means Adapter; the same interface and it may skip the real call means Proxy; the same interface and it always calls through, adding something, means Decorator. A new, simpler method over several objects is a Facade.

The caching repository skips the database on a hit (Proxy), the auditing repository always calls through and logs (Decorator), the legacy DAO wrapper translates numbers and codes (Adapter), and the tracking class combines calls behind one method (Facade).

Finish up

Mark complete & continue

Next: Project: refactoring a legacy ShopLite checkout