Sobes.tech
Senior

How to replace large if-else / switch-case structures with patterns (e.g., Strategy)?

sobes.tech AI

Answer from AI

Large if-else or switch-case structures often lead to complex and hard-to-maintain code. The Strategy pattern helps replace them with a more flexible and extensible architecture.

The idea is to move different behavior variants into separate classes (strategies) that implement a common interface. Then, in the client code, the desired strategy is selected and its method is called.

Example in Java:

// Strategy interface
public interface PaymentStrategy {
    void pay(int amount);
}

// Concrete strategies
public class CreditCardPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Payment by credit card: " + amount);
    }
}

public class PayPalPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Payment via PayPal: " + amount);
    }
}

// Context
public class PaymentContext {
    private PaymentStrategy strategy;

    public void setStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void pay(int amount) {
        strategy.pay(amount);
    }
}

// Usage
PaymentContext context = new PaymentContext();

// Choose strategy based on condition
if (userPrefersCreditCard) {
    context.setStrategy(new CreditCardPayment());
} else {
    context.setStrategy(new PayPalPayment());
}
context.pay(1000);

This approach:

  • Simplifies adding new options (just add a new strategy class)
  • Eliminates bulky conditional operators
  • Improves code readability and testability

Instead of if-else, you can use a Map with keys and strategies for even cleaner code.