Course contentsShow
← Java
Lesson 459 of 2,87011. Polymorphism and Dynamic DispatchFree lesson

Migrating Legacy Code to Pattern Matching

Practice refactoring traditional instanceof-cast code to modern pattern matching for cleaner, safer type tests.

Migrating Legacy Code to Pattern Matching

You'll learn: How to refactor old-style instanceof-cast code into cleaner, safer pattern matching syntax.

The Old Way vs. The Modern Way

Before pattern matching (introduced in Java 16), checking types and accessing subclass members required a verbose three-step dance: test with instanceof, explicitly cast, then use. This pattern appeared everywhere in legacy code:

if (obj instanceof Dog) {
    Dog d = (Dog) obj;  // Manual cast
    d.bark();
}

With pattern matching, you eliminate the cast and introduce the variable in one step:

if (obj instanceof Dog d) {
    d.bark();  // Pattern variable ready to use
}

Practical Refactoring Steps

Before (legacy code):

public void makeSound(Animal animal) {
    if (animal instanceof Dog) {
        Dog dog = (Dog) animal;
        System.out.println(dog.bark());
    } else if (animal instanceof Cat) {
        Cat cat = (Cat) animal;
        System.out.println(cat.meow());
    }
}

After (pattern matching):

public void makeSound(Animal animal) {
    if (animal instanceof Dog dog) {
        System.out.println(dog.bark());
    } else if (animal instanceof Cat cat) {
        System.out.println(cat.meow());
    }
}

Why Migrate?

Pattern matching reduces boilerplate, eliminates the possibility of casting to the wrong type (since the cast is implicit and guaranteed safe), and makes code more readable. It's especially beneficial in methods with multiple type checks or nested conditions.

Key Takeaway: Refactoring legacy instanceof-cast-use patterns to pattern matching removes redundant code, improves safety by eliminating manual casts, and makes your type-checking logic clearer and more maintainable.