• Shift Elevate
  • Posts
  • Switch Statements: Replace Conditional with Polymorphism | Clean Code

Switch Statements: Replace Conditional with Polymorphism | Clean Code

Switch statements that handle object types or behaviors are a common code smell that violates the Open Closed Principle.

We will see how we can refactor them using polymorphism.

Clean Code Reference

⚠️ Code Smell: Switch Statements
Refactoring: Replace Conditional with Polymorphism
🎯 Goal: Extensible behavior without modifying existing code

The Switch Statements code smell occurs when switch statements or if-else chains handle different object types or behaviors. The Replace Conditional with Polymorphism refactoring technique eliminates these conditionals by using inheritance and polymorphism to handle different behaviors.

The Code Smell: Switch Statements

Switch Statements is a code smell that violates the Open Closed Principle. When switch statements or if-else chains handle different object types or behaviors, the code becomes rigid and difficult to extend. Adding new cases requires modifying existing code, which can introduce bugs.

Symptoms

Impact

Switch statements handling object types

Violates Open Closed Principle

If-else chains for behavior selection

Difficult to extend

Repeated switch logic across methods

Code duplication

Here's a typical example of switch statement code smell:

public class PaymentProcessor {
    public double calculateDiscount(String customerType, double amount) {
        switch (customerType) {
            case "REGULAR":
                return amount * 0.05; // 5% discount
            case "PREMIUM":
                return amount * 0.10; // 10% discount
            case "VIP":
                return amount * 0.15; // 15% discount
            default:
                return 0.0;
        }
    }
    
    public String getWelcomeMessage(String customerType) {
        switch (customerType) {
            case "REGULAR":
                return "Welcome! Enjoy your shopping.";
            case "PREMIUM":
                return "Welcome back! You have premium benefits.";
            case "VIP":
                return "Welcome VIP! Exclusive offers await you.";
            default:
                return "Welcome!";
        }
    }
}

This code has multiple switch statements handling the same customer types, violating the Open Closed Principle. Adding a new customer type requires modifying multiple methods, which can introduce bugs and make the code harder to maintain.

The Refactoring: Replace Conditional with Polymorphism

The Replace Conditional with Polymorphism refactoring technique eliminates switch statements by creating a hierarchy of classes that handle different behaviors through inheritance and polymorphism. This makes the code extensible without modifying existing code.

Step by Step Refactoring Process:

  1. Identify the switch statement that handles different object types or behaviors.

  2. Create an abstract base class or interface for the common behavior.

  3. Create concrete subclasses for each case in the switch statement.

  4. Move the behavior logic from the switch cases to the appropriate subclasses.

  5. Replace the switch statement with polymorphic method calls.

Here's the refactored version:

// Abstract base class
public abstract class Customer {
    protected String name;
    
    public Customer(String name) {
        this.name = name;
    }
    
    public abstract double calculateDiscount(double amount);
    public abstract String getWelcomeMessage();
}

// Concrete implementations
public class RegularCustomer extends Customer {
    public RegularCustomer(String name) {
        super(name);
    }
    
    @Override
    public double calculateDiscount(double amount) {
        return amount * 0.05; // 5% discount
    }
    
    @Override
    public String getWelcomeMessage() {
        return "Welcome! Enjoy your shopping.";
    }
}

public class PremiumCustomer extends Customer {
    public PremiumCustomer(String name) {
        super(name);
    }
    
    @Override
    public double calculateDiscount(double amount) {
        return amount * 0.10; // 10% discount
    }
    
    @Override
    public String getWelcomeMessage() {
        return "Welcome back! You have premium benefits.";
    }
}

public class VipCustomer extends Customer {
    public VipCustomer(String name) {
        super(name);
    }
    
    @Override
    public double calculateDiscount(double amount) {
        return amount * 0.15; // 15% discount
    }
    
    @Override
    public String getWelcomeMessage() {
        return "Welcome VIP! Exclusive offers await you.";
    }
}

// Refactored payment processor
public class PaymentProcessor {
    public double calculateDiscount(Customer customer, double amount) {
        return customer.calculateDiscount(amount);
    }
    
    public String getWelcomeMessage(Customer customer) {
        return customer.getWelcomeMessage();
    }
}

Benefits of Replace Conditional with Polymorphism

Benefit

Description

Follows Open Closed Principle

New customer types can be added by creating new subclasses without modifying existing code, making the system extensible and reducing the risk of introducing bugs.

Eliminates Code Duplication

The switch logic is centralized in the appropriate customer classes, removing the need to repeat the same conditional logic across multiple methods.

Improves Maintainability

Each customer type's behavior is encapsulated in its own class, making it easier to understand, test, and modify individual behaviors.

When to Apply Replace Conditional with Polymorphism Refactoring

  • Switch statements or if-else chains handling different object types.

  • Repeated switch logic across multiple methods.

  • When adding new cases requires modifying existing code.

  • When the switch logic violates the Open Closed Principle.

  • When you want to make the code more extensible and maintainable.

Apply Replace Conditional with Polymorphism refactoring to one switch statement in your current project today. Start with the switch statement that handles the most complex business logic.

Repository & Resources

Complete Code Examples: Clean Code Repository

Find the complete implementation of Switch Statements refactoring and other clean code techniques in our dedicated repository. Each example includes:

  • Before and after code comparisons

  • Unit tests demonstrating the improvements

Found this helpful? Share it with a colleague who's struggling with switch statements. Have questions about refactoring polymorphic solutions in your codebase? Email us directly, we read every message and the best questions become future newsletter topics.