Skip to lesson

When a pattern makes code worse

ShopLite's greeting, coupon check and delivery charge each grew a factory, a manager and a strategy around a one-line rule. Nobody can find where the rule lives, and every change touches many files.

Pattern fever: factories of factories for one class

Pattern fever is adding design patterns because they look professional, not because the code has the problem they solve. Each extra pattern adds types, files and jumps.

ShopLite wants to print one welcome line. The code below does it with seven types: interfaces, a factory, a provider and a service.

Example 1 · Seven types for one welcome line

PatternFeverDemo.javaJava
// Seven types to print one welcome lineinterface GreetingStrategy {    String greet(String name);}
class DefaultGreetingStrategy implements GreetingStrategy {    public String greet(String name) {        return "Welcome to ShopLite, " + name;    }}
interface GreetingStrategyFactory {    GreetingStrategy create();}
class DefaultGreetingStrategyFactory implements GreetingStrategyFactory {    public GreetingStrategy create() {        return new DefaultGreetingStrategy();    }}
class GreetingStrategyFactoryProvider {    private static final GreetingStrategyFactoryProvider INSTANCE = new GreetingStrategyFactoryProvider();
    private GreetingStrategyFactoryProvider() { }
    static GreetingStrategyFactoryProvider getInstance() {        return INSTANCE;    }
    GreetingStrategyFactory getFactory() {        return new DefaultGreetingStrategyFactory();    }}
class GreetingService {    String welcome(String name) {        return GreetingStrategyFactoryProvider.getInstance().getFactory().create().greet(name);    }}
public class PatternFeverDemo {    public static void main(String[] args) {        System.out.println(new GreetingService().welcome("Riya"));        System.out.println("Types involved: 7 (2 interfaces, 4 classes, 1 demo)");    }}
Output
Welcome to ShopLite, Riya
Types involved: 7 (2 interfaces, 4 classes, 1 demo)

What this code does

  • A provider singleton returns a factory that creates a strategy, yet there is only one strategy and it returns one string.
  • Nothing here varies or needs a fake in tests, so every layer is cost without benefit.

A common sign is a chain like a factory provider that returns a factory that creates a strategy, when only one strategy exists and none is planned. A reader must open six or seven types to learn that the program prints one sentence, and every extra type needs a name, tests and maintenance.

YAGNI and KISS as checks

YAGNI stands for "You aren't gonna need it". It means do not build for a need you only imagine; build it when a real second case arrives.

ShopLite's coupon check has exactly one rule today. The code below builds a rule engine for it, then a plain method that does the same job.

Example 2 · A rule engine with one rule

YagniCouponDemo.javaJava
import java.util.ArrayList;import java.util.List;
// Built "for the future": a rule engine with one rule in itinterface CouponRule {    String check(String code, int cartTotal);   // null means ok}
class MinimumCartRule implements CouponRule {    public String check(String code, int cartTotal) {        return cartTotal >= 500 ? null : "Cart must be at least Rs. 500";    }}
class CouponRuleEngine {    private final List<CouponRule> rules = new ArrayList<>();
    void addRule(CouponRule rule) {        rules.add(rule);    }
    String validate(String code, int cartTotal) {        for (CouponRule r : rules) {            String problem = r.check(code, cartTotal);            if (problem != null) return problem;        }        return "OK";    }}
public class YagniCouponDemo {    // What the shop actually needs today    static String validate(int cartTotal) {        return cartTotal >= 500 ? "OK" : "Cart must be at least Rs. 500";    }
    public static void main(String[] args) {        CouponRuleEngine engine = new CouponRuleEngine();        engine.addRule(new MinimumCartRule());
        for (int total : new int[] {350, 800}) {            System.out.println("Rs. " + total + " engine: " + engine.validate("FEST10", total)                    + " | plain: " + validate(total));        }    }}
Output
Rs. 350 engine: Cart must be at least Rs. 500 | plain: Cart must be at least Rs. 500
Rs. 800 engine: OK | plain: OK

What this code does

  • The engine and the plain method give the same answers for both carts.
  • The engine was built for rules that may never come; YAGNI says write the plain method and refactor when a second real rule appears.

KISS ("Keep it simple") means choose the simplest design that solves today's problem clearly. YAGNI and KISS together are a quick test before adding a pattern.

A coupon rule engine with one rule fails both: the plain method is shorter and just as correct. If a second and third rule really arrive, refactoring to a rule list then is cheap, especially with tests.

Predict the output

Add the pattern or not?

Apply YAGNI and KISS to each ShopLite situation.

Round 1 of 2

What do YAGNI and KISS suggest?

ShopLite has one delivery rule: free from Rs. 499, else Rs. 40.
A teammate proposes DeliveryChargeStrategy, a factory and a manager.

The cost of indirection

Indirection is each extra layer between a caller and the code that does the work: a facade, a manager, a factory, a strategy. Each layer adds one more file to open and one more jump while debugging.

Each layer is one more jump. The code below traces one delivery-charge call through four classes to reach a one-line rule.

Example 3 · Tracing the hops to a one-line rule

IndirectionDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Trace {    static final List<String> hops = new ArrayList<>();}
interface DeliveryChargeStrategy {    int charge(int total);}
class FlatDeliveryChargeStrategy implements DeliveryChargeStrategy {    public int charge(int total) {        Trace.hops.add("FlatDeliveryChargeStrategy");        return total >= 499 ? 0 : 40;    }}
class DeliveryChargeStrategyFactory {    DeliveryChargeStrategy create() {        Trace.hops.add("DeliveryChargeStrategyFactory");        return new FlatDeliveryChargeStrategy();    }}
class DeliveryChargeManager {    private final DeliveryChargeStrategyFactory factory = new DeliveryChargeStrategyFactory();
    int compute(int total) {        Trace.hops.add("DeliveryChargeManager");        return factory.create().charge(total);    }}
class CheckoutFacade {    private final DeliveryChargeManager manager = new DeliveryChargeManager();
    int deliveryCharge(int total) {        Trace.hops.add("CheckoutFacade");        return manager.compute(total);    }}
public class IndirectionDemo {    static int deliveryCharge(int total) {        return total >= 499 ? 0 : 40;    }
    public static void main(String[] args) {        int layered = new CheckoutFacade().deliveryCharge(350);        System.out.println("Layered: Rs. " + layered + " after " + Trace.hops.size() + " hops");        System.out.println("  " + String.join(" -> ", Trace.hops));        System.out.println("Direct:  Rs. " + deliveryCharge(350) + " in one method");    }}
Output
Layered: Rs. 40 after 4 hops
  CheckoutFacade -> DeliveryChargeManager -> DeliveryChargeStrategyFactory -> FlatDeliveryChargeStrategy
Direct:  Rs. 40 in one method

What this code does

  • The trace shows four classes between the caller and total >= 499 ? 0 : 40.
  • The direct method gives the same Rs. 40 and is the only place a reader needs to look.

Each layer can be worth it, but trace one call to check. If four classes only pass the call along to reach a one-line rule, those layers cost more than they give.

Simplifying an over-engineered design

A seam is a place in the code where behaviour really varies, or where a test needs to swap a part, such as ShopLite's payment gateway. Keep abstractions at seams and remove them elsewhere.

Simplifying is refactoring the other way: remove layers that add nothing, and keep real seams. The code below keeps PaymentGateway and turns the rest into plain methods.

Example 4 · Simplified back to plain code, seam kept

SimplifiedDemo.javaJava
import java.math.BigDecimal;
// Keep an interface only where there is a real seam: payment providers really differ and tests need fakesinterface PaymentGateway {    boolean charge(String orderId, BigDecimal amount);}
class UpiPaymentGateway implements PaymentGateway {    public boolean charge(String orderId, BigDecimal amount) {        System.out.println("UPI charge " + orderId + " Rs. " + amount);        return true;    }}
// Was: GreetingStrategy + factory + provider singleton. Now: one method.class Messages {    static String welcome(String name) {        return "Welcome to ShopLite, " + name;    }}
// Was: DeliveryChargeStrategy + factory + manager + facade. Now: one class with one rule.class Checkout {    private final PaymentGateway payments;
    Checkout(PaymentGateway payments) {        this.payments = payments;    }
    static int deliveryCharge(int total) {        return total >= 499 ? 0 : 40;    }
    void pay(String orderId, int itemsTotal) {        int total = itemsTotal + deliveryCharge(itemsTotal);        payments.charge(orderId, BigDecimal.valueOf(total));    }}
public class SimplifiedDemo {    public static void main(String[] args) {        System.out.println(Messages.welcome("Riya"));        new Checkout(new UpiPaymentGateway()).pay("ORD-71", 350);        new Checkout(new UpiPaymentGateway()).pay("ORD-72", 650);    }}
Output
Welcome to ShopLite, Riya
UPI charge ORD-71 Rs. 390
UPI charge ORD-72 Rs. 650

What this code does

  • The greeting and delivery charge are now plain methods; the output of the old designs is unchanged.
  • PaymentGateway stays an interface because providers really differ and tests need a fake: that is a real seam.

Inline one-implementation interfaces, single-use factories and pass-through managers. Keep an interface where several implementations exist or tests need fakes.

Use the same safety rule as any refactor: the same output before and after. In ShopLite, the payment gateway stays an interface because providers really differ; the greeting and the delivery charge become plain methods.

Order of execution

Simplify in safe steps

Put the steps for removing the delivery-charge layers in order.

Questions to ask before introducing a pattern

Before adding a pattern, answer a few questions honestly. If most answers point to "not now", write plain code and refactor later when the need is real.

  • Which problem do I have today, and does this pattern solve that problem?
  • How many variants exist now, and how often have new ones arrived?
  • Will a new teammate understand the code faster with the pattern or without it?
  • What does it cost in classes, files and jumps, and can I add it later with a small refactor?
A useful rule of thumb: tolerate duplication or a switch twice; on the third similar case, refactor to a pattern.

Next step

Check your understanding

12 quick questions