Course contentsShow
← Software Engineering
Lesson 351 of 1,93310. RefactoringFree lesson

Replace Conditional with Polymorphism

Transform complex conditional logic into polymorphic class hierarchies for more maintainable and extensible code.

Replace Conditional with Polymorphism

What you'll learn: How to eliminate repetitive conditional logic by delegating behavior to polymorphic class hierarchies.

The Core Problem

When you have complex if, else if, or switch statements that check an object's type or state to decide what behavior to execute, you're missing an opportunity. Each time you need to add a new type or behavior, you must hunt down and update every conditional. This is fragile and hard to maintain.

The Polymorphic Solution

Instead of asking "What type are you?" and branching, create a class hierarchy where each subclass implements the varying behavior. Let polymorphism automatically dispatch to the correct method based on the object's actual type.

Before (conditional):

def get_speed(animal_type):
    if animal_type == "bird":
        return 50
    elif animal_type == "cheetah":
        return 70
    elif animal_type == "turtle":
        return 2

After (polymorphic):

class Animal:
    def get_speed(self):
        pass

class Bird(Animal):
    def get_speed(self):
        return 50

class Cheetah(Animal):
    def get_speed(self):
        return 70

class Turtle(Animal):
    def get_speed(self):
        return 2

Now calling animal.get_speed() automatically executes the right implementation—no conditionals needed.

When to Apply This

Use this refactoring when:

  • The same conditional appears in multiple places
  • You're checking type codes or categories repeatedly
  • Adding new types requires touching many conditionals

The Analogy

Think of a vending machine. Instead of one giant controller asking "Is this a candy button? A soda button?" each button knows what it dispenses. Press it, and it handles its own behavior.

Key Takeaway: Replace type-checking conditionals with polymorphic class hierarchies—let objects handle their own behavior variations, making your code more extensible and maintainable.