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 12: Dealing with Inheritance
Key Insight 4 from this chapter

Managing Subclass Hierarchies (Addition and Removal)

Key Insight

Class hierarchies are dynamic structures that require tools to add, remove, or merge classes as a software system evolves. These refactorings improve program structure, reduce complexity, and ensure the model accurately reflects the domain. 'Extract Superclass' is a refactoring applied when two or more classes exhibit similar data or behavior, allowing these commonalities to be consolidated into a new superclass. This approach promotes code reuse and simplifies the overall design, often serving as a simpler initial choice compared to 'Extract Class' (delegation), with the flexibility to transition to delegation later if needed.

The mechanics for 'Extract Superclass' begin by creating an empty superclass and making the original classes its subclasses, adjusting constructors as necessary. Common elements are then moved to the superclass iteratively using 'Pull Up Constructor Body', 'Pull Up Method', and 'Pull Up Field'. Remaining methods in subclasses are examined for further commonalities, which can then be extracted and pulled up. Finally, clients of the original classes are considered for adjustment to utilize the new superclass interface. Comprehensive testing is performed after each significant step to maintain system integrity.

'Remove Subclass' is used when a subclass provides insufficient unique value to justify its separate existence, often because its variations have moved or were never fully implemented. This refactoring replaces the subclass with a field on its superclass. Mechanics involve encapsulating constructor calls with 'Replace Constructor with Factory Function' and moving `instanceof` type tests into superclass methods (e.g., `isMale(p)` becomes `p.isMale`). A field is added to the superclass to represent the former subclass type, and methods are updated to use this field. The subclass is then deleted, and tests are run. 'Collapse Hierarchy' is used when a class and its parent are no longer distinct enough; all elements are moved to one class (based on the better name), references are adjusted, and the empty class is removed.

📚 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.