SOLID & Design Patterns Interview Question #146

How would you refactor a large switch statement that selects behavior by type?

Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced

Quick Interview Answer

First determine whether the switch represents genuinely varying behavior. If new cases are added frequently and each case contains substantial logic, Strategy or polymorphism can move each behavior into a focused implementation.

Detailed Explanation

First determine whether the switch represents genuinely varying behavior. If new cases are added frequently and each case contains substantial logic, Strategy or polymorphism can move each behavior into a focused implementation.

Do not replace every small switch. A short stable switch can be clearer than a hierarchy of classes. Refactoring is justified when it improves change isolation and readability.

Code Example

public interface IDiscountStrategy
{
    decimal Apply(decimal total);
}

public class VipDiscount : IDiscountStrategy { }
public class SeasonalDiscount : IDiscountStrategy { }

// Selection can be handled by a factory
// or keyed DI registration.