From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewRefactoring by Moving Common Elements Up the Hierarchy
Key Insight
Refactoring by moving common elements up the hierarchy primarily aims to eliminate duplicate code and data across subclasses, which are breeding grounds for bugs. Duplication risks inconsistencies if alterations are made to one copy but not another. 'Pull Up Method' addresses this by moving identical methods, or those that can be parameterized to be identical, from subclasses to a superclass. If methods have a similar overall flow but differ in details, 'Form Template Method' is considered first. A key challenge arises if the method body in a subclass refers to features not present in the superclass, necessitating that those fields or methods be pulled up first.
The mechanics for 'Pull Up Method' involve inspecting methods for exact identity; if functionally identical but not literally, they are refactored until they are. It is crucial to ensure all method calls and field references within the method body are accessible from the superclass. If signatures differ, they are unified using 'Change Function Declaration'. A new method is then created in the superclass, the body of one subclass method is copied, static checks are run, and subclass methods are deleted one by one, with testing after each deletion. 'Pull Up Field' operates similarly, moving duplicate fields from subclasses to a superclass. Mechanics include inspecting field usage, renaming fields for consistency, creating a new accessible field in the superclass, deleting subclass fields, and testing. In dynamic languages, field pulling is often an implicit outcome of pulling up constructor bodies.
'Pull Up Constructor Body' targets common initialization logic in subclass constructors. Due to special rules governing constructors, a direct 'Extract Function' followed by 'Pull Up Method' is not always feasible. The process involves defining a superclass constructor (if none exists) and ensuring it is called by subclass constructors. Common statements are moved just after the `super()` call using 'Slide Statements'. The common code is then removed from subclasses and placed in the superclass constructor, with any referenced constructor parameters passed to `super()`. Testing is crucial throughout this process. If some common code cannot move to the constructor's start, 'Extract Function' followed by 'Pull Up Method' can be used on that specific part.
📚 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.