Cover of Refactoring by Martin Fowler, Kent Beck - Business and Economics Book

From "Refactoring"

Author: Martin Fowler, Kent Beck
Publisher: Addison-Wesley Professional
Year: 1999
Category: Computers

🎧 Free Preview Complete

You've listened to your free 10-minute preview.
Sign up free to continue listening to the full summary.

🎧 Listen to Summary

Free 10-min Preview
0:00
Speed:
10:00 free remaining
Chapter 10: Simplifying Conditional Logic
Key Insight 4 from this chapter

Replace Conditional with Polymorphism

Key Insight

Complex conditional logic, particularly instances involving multiple functions containing `switch` statements that branch on the same 'type code,' represents one of the most challenging aspects of program comprehension. This duplication of switching logic based on type creates brittle and hard-to-modify code, as any change to type-specific behavior requires modifications across all such conditional structures. This problem highlights a need for a more structured approach to managing type-dependent variations.

Polymorphism offers a powerful solution by separating type-specific logic into distinct classes. Instead of `switch/case` or `if/else` chains, each type (e.g., 'EuropeanSwallow', 'AfricanSwallow', 'NorwegianBlueParrot') is represented by its own class, and the varying behavior (e.g., `plumage`, `airSpeedVelocity`) is implemented as overridden methods within these classes. This approach centralizes specific behaviors, making the system more extensible and easier to reason about, especially for cases with a clear base behavior and multiple variants. While polymorphism is not a universal replacement for all conditionals, it is exceptionally effective for managing type-driven complexity.

The refactoring process involves creating classes for each polymorphic behavior, often with a factory function to instantiate the correct type. The original conditional function is moved to a superclass. Then, for each 'leg' of the conditional (e.g., each `case` in a `switch` statement), a subclass method is created to override the superclass method, containing the specific logic for that type. A default case can remain in the superclass or be declared abstract. An example is transforming bird `plumage` and `airSpeedVelocity` calculations, initially using `switch` statements on `bird.type`, into a `Bird` superclass and specialized subclasses (e.g., `EuropeanSwallow`, `AfricanSwallow`), where each subclass implements its unique `plumage` and `airSpeedVelocity` methods. Another complex example involves refactoring a `Rating` system for ship voyages, abstracting the 'Experienced China' voyage logic into a subclass to simplify the base rating calculations.

📚 Continue Your Learning Journey — No Payment Required

Access the complete Refactoring summary with audio narration, key takeaways, and actionable insights from Martin Fowler, Kent Beck.