Skip to lesson

Refactoring long if-else and switch to Strategy

ShopLite's shipping code repeats the same switch on the delivery method in three places. Adding same-day delivery means editing all three, and missing one breaks checkout only for that option.

Smell: the same switch in several methods

A code smell is a sign in the code that the design may cause trouble later. The code still works, but changing it safely is getting harder.

ShopLite's shipping class has cost, days and label. Each one switches on the same method name. Read the code once and spot the repeat.

Example 1 · The smell: one switch copied into three methods

RepeatedSwitchDemo.javaJava
// Legacy ShopLite shipping code: the same switch appears in three methodsclass ShippingCalculator {    int cost(String method, int weightKg, int orderTotal) {        switch (method) {            case "STANDARD":                if (orderTotal >= 499) return 0;                return 40 + Math.max(0, weightKg - 2) * 15;            case "EXPRESS":                return 90 + Math.max(0, weightKg - 2) * 25;            case "PICKUP":                return 0;            default:                throw new IllegalArgumentException("Unknown method: " + method);        }    }
    int days(String method) {        switch (method) {            case "STANDARD": return 5;            case "EXPRESS": return 2;            case "PICKUP": return 1;            default: throw new IllegalArgumentException("Unknown method: " + method);        }    }
    String label(String method) {        switch (method) {            case "STANDARD": return "Standard delivery";            case "EXPRESS": return "Express delivery";            case "PICKUP": return "Store pickup";            default: throw new IllegalArgumentException("Unknown method: " + method);        }    }}
public class RepeatedSwitchDemo {    public static void main(String[] args) {        ShippingCalculator calc = new ShippingCalculator();        for (String m : new String[] {"STANDARD", "EXPRESS", "PICKUP"}) {            System.out.println(calc.label(m) + ": Rs. " + calc.cost(m, 4, 350) + ", days: " + calc.days(m));        }    }}
Output
Standard delivery: Rs. 70, days: 5
Express delivery: Rs. 140, days: 2
Store pickup: Rs. 0, days: 1

What this code does

  • cost, days and label each switch on the same method name, so the rules for Express are spread over three places.
  • Adding a fourth option means editing all three switches, and a missed one only fails at runtime in its default branch.

This is the repeated switch smell: one switch on a type code, such as "STANDARD" or "EXPRESS", copied into several methods.

Each case's rules are spread across the class. Adding SAME_DAY means finding and editing every switch, and a missed one throws from its default branch, often only for that new option.

Predict the output

Spot the missed switch

ShopLite adds SAME_DAY to some switches only. What happens at run time?

Round 1 of 2

Which line fails, and how?

ShippingCalculator calc = new ShippingCalculator();
// SAME_DAY was added to cost() and days(), not to label()
int price = calc.cost("SAME_DAY", 4, 350);
int days = calc.days("SAME_DAY");
String text = calc.label("SAME_DAY");

Step-by-step refactor, output kept identical

Refactoring means changing the structure of code without changing what it does. The results stay exactly the same; only the inside becomes easier to change.

Refactor in small steps, each checked against the old code:

  1. Record the current output for a grid of inputs, including the edges (Rs. 498 and Rs. 499, 2 kg and 3 kg).
  2. Create an interface with one method per switch: cost, days, label.
  3. Create one class per case and move each switch arm into it, unchanged.
  4. Replace each switch with a call on the chosen object.
  5. Compare the new results with the recorded ones; any mismatch means a step changed behaviour.
Before: one ShippingCalculator class with three switches, cost, days and label, each repeating the cases STANDARD, EXPRESS and PICKUP. After: a ShippingOption interface, one class per option, and one ShippingOptions map. A new option is one new class and one map line.

Example 2 · Refactor with a safety net

SafeRefactorDemo.javaJava
import java.util.List;
// Before: kept unchanged so we can compare against itclass LegacyShipping {    int cost(String method, int weightKg, int orderTotal) {        switch (method) {            case "STANDARD":                if (orderTotal >= 499) return 0;                return 40 + Math.max(0, weightKg - 2) * 15;            case "EXPRESS":                return 90 + Math.max(0, weightKg - 2) * 25;            case "PICKUP":                return 0;            default:                throw new IllegalArgumentException("Unknown method: " + method);        }    }
    int days(String method) {        switch (method) {            case "STANDARD": return 5;            case "EXPRESS": return 2;            case "PICKUP": return 1;            default: throw new IllegalArgumentException("Unknown method: " + method);        }    }}
// After: one interface, one class per former switch arminterface ShippingOption {    int cost(int weightKg, int orderTotal);    int days();    String label();}
class StandardShipping implements ShippingOption {    public int cost(int weightKg, int orderTotal) {        if (orderTotal >= 499) return 0;        return 40 + Math.max(0, weightKg - 2) * 15;    }    public int days() { return 5; }    public String label() { return "Standard delivery"; }}
class ExpressShipping implements ShippingOption {    public int cost(int weightKg, int orderTotal) {        return 90 + Math.max(0, weightKg - 2) * 25;    }    public int days() { return 2; }    public String label() { return "Express delivery"; }}
class StorePickup implements ShippingOption {    public int cost(int weightKg, int orderTotal) { return 0; }    public int days() { return 1; }    public String label() { return "Store pickup"; }}
public class SafeRefactorDemo {    public static void main(String[] args) {        LegacyShipping old = new LegacyShipping();        List<String> names = List.of("STANDARD", "EXPRESS", "PICKUP");        List<ShippingOption> options = List.of(new StandardShipping(), new ExpressShipping(), new StorePickup());
        int checked = 0;        int mismatches = 0;        for (int i = 0; i < names.size(); i++) {            for (int weight : new int[] {1, 2, 3, 10}) {                for (int total : new int[] {0, 498, 499, 2000}) {                    checked++;                    if (old.cost(names.get(i), weight, total) != options.get(i).cost(weight, total)) {                        mismatches++;                        System.out.println("MISMATCH " + names.get(i) + " " + weight + "kg Rs. " + total);                    }                }            }            if (old.days(names.get(i)) != options.get(i).days()) {                mismatches++;            }        }        System.out.println("Checked " + checked + " cost cases and 3 delivery times: " + mismatches + " mismatches");    }}
Output
Checked 48 cost cases and 3 delivery times: 0 mismatches

What this code does

  • The legacy class stays in the program as the reference. Each new class holds one former switch arm, copied without changes.
  • The loop compares old and new on 48 cost cases, including the Rs. 498 and Rs. 499 edges, plus the delivery times: zero mismatches means behaviour is unchanged.

The loop is a characterisation check: it records what the old code does now, on many inputs including the edges (Rs. 498 and 499), and compares the new code against it. Zero mismatches means the behaviour is unchanged.

Only after the check passes should you tidy the new classes. Moving and improving in the same step is how a boundary bug sneaks in.

Find the bug

Which line changed behaviour?

The comparison reports a mismatch. Click the line that broke it.

Mismatch at exactly Rs. 499: old gives 0, new gives a charge.

Round 1 of 2
Copy the arms exactly first, and tidy them only after the comparison passes. Mixing "move" and "improve" in one step is how boundary bugs sneak in.

Moving the choice to one place: a map or factory

A registry is one map from a code, such as "EXPRESS", to its strategy object. It is the only place in the program that knows every option.

Something must still turn the text "EXPRESS" into an ExpressShipping object. The program below puts that choice in one map and adds same-day delivery.

Example 3 · One place chooses the strategy

RegistryDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
interface ShippingOption {    int cost(int weightKg, int orderTotal);    int days();    String label();}
class StandardShipping implements ShippingOption {    public int cost(int weightKg, int orderTotal) {        if (orderTotal >= 499) return 0;        return 40 + Math.max(0, weightKg - 2) * 15;    }    public int days() { return 5; }    public String label() { return "Standard delivery"; }}
class ExpressShipping implements ShippingOption {    public int cost(int weightKg, int orderTotal) {        return 90 + Math.max(0, weightKg - 2) * 25;    }    public int days() { return 2; }    public String label() { return "Express delivery"; }}
class StorePickup implements ShippingOption {    public int cost(int weightKg, int orderTotal) { return 0; }    public int days() { return 1; }    public String label() { return "Store pickup"; }}
// New option: one new class, nothing else editedclass SameDayShipping implements ShippingOption {    public int cost(int weightKg, int orderTotal) { return 149; }    public int days() { return 0; }    public String label() { return "Same-day delivery"; }}
// The only place that maps a name to a strategyclass ShippingOptions {    private final Map<String, ShippingOption> byCode = new LinkedHashMap<>();
    ShippingOptions() {        byCode.put("STANDARD", new StandardShipping());        byCode.put("EXPRESS", new ExpressShipping());        byCode.put("PICKUP", new StorePickup());        byCode.put("SAME_DAY", new SameDayShipping());    }
    ShippingOption forCode(String code) {        ShippingOption option = byCode.get(code);        if (option == null) {            throw new IllegalArgumentException("Unknown method: " + code);        }        return option;    }
    Iterable<String> codes() {        return byCode.keySet();    }}
public class RegistryDemo {    public static void main(String[] args) {        ShippingOptions options = new ShippingOptions();        for (String code : options.codes()) {            ShippingOption o = options.forCode(code);            System.out.println(o.label() + ": Rs. " + o.cost(4, 350) + ", days: " + o.days());        }        try {            options.forCode("DRONE");        } catch (IllegalArgumentException e) {            System.out.println(e.getMessage());        }    }}
Output
Standard delivery: Rs. 70, days: 5
Express delivery: Rs. 140, days: 2
Store pickup: Rs. 0, days: 1
Same-day delivery: Rs. 149, days: 0
Unknown method: DRONE

What this code does

  • ShippingOptions is the only class that maps a code to an object. Same-day delivery needed one new class and one put line.
  • Unknown codes fail in one place with a clear message, instead of in every former switch.

Same-day delivery needed one new class and one put line. Checkout only calls option.cost(...), so it did not change. That is the open/closed principle from the OOP section at work.

Enum with behaviour as a lighter option

An enum with behaviour is an enum whose constants carry their own fields and method bodies. It gives a small, fixed set of options most of Strategy's benefit with less code.

An enum can give each constant its own method body. Below, the three shipping methods become one enum, with no map and no extra files.

Example 4 · Enum constants with their own behaviour

EnumStrategyDemo.javaJava
enum ShippingMethod {    STANDARD("Standard delivery", 5) {        int cost(int weightKg, int orderTotal) {            if (orderTotal >= 499) return 0;            return 40 + Math.max(0, weightKg - 2) * 15;        }    },    EXPRESS("Express delivery", 2) {        int cost(int weightKg, int orderTotal) {            return 90 + Math.max(0, weightKg - 2) * 25;        }    },    PICKUP("Store pickup", 1) {        int cost(int weightKg, int orderTotal) {            return 0;        }    };
    private final String label;    private final int days;
    ShippingMethod(String label, int days) {        this.label = label;        this.days = days;    }
    abstract int cost(int weightKg, int orderTotal);   // each constant must implement it
    String label() { return label; }    int days() { return days; }}
public class EnumStrategyDemo {    public static void main(String[] args) {        for (ShippingMethod m : ShippingMethod.values()) {            System.out.println(m.label() + ": Rs. " + m.cost(4, 350) + ", days: " + m.days());        }        ShippingMethod chosen = ShippingMethod.valueOf("EXPRESS");        System.out.println("From text: " + chosen + " costs Rs. " + chosen.cost(1, 999));    }}
Output
Standard delivery: Rs. 70, days: 5
Express delivery: Rs. 140, days: 2
Store pickup: Rs. 0, days: 1
From text: EXPRESS costs Rs. 90

What this code does

  • Each constant has a body that implements the abstract cost, and the shared fields hold the label and days.
  • ShippingMethod.valueOf("EXPRESS") turns text into a constant, so no map is needed for a fixed set.

An abstract method in the enum forces every constant to implement it, so a new constant cannot forget its cost rule. valueOf("EXPRESS") replaces the map lookup.

Use classes instead when options come from plugins or configuration, or need their own dependencies.

Fix the error

Fix the enum constant

Read the real compiler error, then pick the line that fixes it.

EXPRESS must implement the abstract cost method.

enum ShippingMethod {
STANDARD("Standard delivery", 5) {
int cost(int kg, int total) { return 40; }
},
EXPRESS("Express delivery", 2),
PICKUP("Store pickup", 1) {
int cost(int kg, int total) { return 0; }
};
ShippingMethod(String label, int days) { }
abstract int cost(int kg, int total);
}

Error

ShippingMethod.java:5: error: ShippingMethod is abstract; cannot be instantiated
    EXPRESS("Express delivery", 2),
           ^

When a short switch should stay a switch

A switch expression is a switch that returns a value, written with -> arms. On an enum, the compiler checks that every constant is covered.

A short switch in one place is fine as it is. The program below picks a badge colour for an order status with one switch expression.

Example 5 · A switch that should stay

KeepSwitchDemo.javaJava
enum OrderStatus { PLACED, PAID, SHIPPED, DELIVERED, CANCELLED }
public class KeepSwitchDemo {    // One switch, used in one place, simple values: this is fine as it is    static String badgeColour(OrderStatus status) {        return switch (status) {            case PLACED, PAID -> "blue";            case SHIPPED -> "orange";            case DELIVERED -> "green";            case CANCELLED -> "grey";        };    }
    public static void main(String[] args) {        for (OrderStatus s : OrderStatus.values()) {            System.out.println(s + " -> " + badgeColour(s));        }    }}
Output
PLACED -> blue
PAID -> blue
SHIPPED -> orange
DELIVERED -> green
CANCELLED -> grey

What this code does

  • The badge colour is chosen in one place, with simple values, so a switch expression is the clearest code.
  • The switch expression covers every OrderStatus constant; if a constant is added later, the compiler reports the missing case.

Keep the switch when it appears in one place, has a few simple cases and rarely changes. Refactor when the repeated-switch smell appears, when each case has real logic, or when new cases arrive often.

How to choose:

  • Stay a switch: one place, a few simple values, stable cases.
  • Enum with behaviour: a fixed small set, some logic per case.
  • Strategy classes plus a map: cases with real logic, added often, or with their own dependencies.

Next step

Check your understanding

12 quick questions