From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewArchitectural Refactorings: Split Phase and Polymorphism
Key Insight
To address evolving requirements, such as generating reports in different formats (e.g., HTML) without duplicating core logic, architectural refactorings like 'Split Phase' are employed. This technique divides the code into distinct calculation and rendering phases. The first phase computes all necessary data and stores it in an intermediate data structure, which is then passed to the second phase responsible for formatting and presentation.
Initially, the entire reporting function, including its nested calculation functions, is extracted into a top-level rendering function (e.g., `renderPlainText`). An intermediate data object is then introduced, progressively populated with customer information, performance details (enriched with play data, amount, and volume credits), and finally, total calculations. This separation allows the calculation logic to reside independently, facilitating reuse across multiple rendering functions, such as `renderHtml`.
To accommodate new business rules and play categories, 'Replace Conditional with Polymorphism' is utilized. This involves creating a base `PerformanceCalculator` class and subclasses (e.g., `TragedyCalculator`, `ComedyCalculator`) to encapsulate type-specific calculation logic. A factory function (e.g., `createPerformanceCalculator`) selects and instantiates the correct subclass based on the play type, thereby replacing complex `switch` statements with a more extensible and maintainable object-oriented hierarchy. This structure groups related calculations and simplifies the addition of future play types.
📚 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.