Refactoring Push Down Method
ProblemIs behavior implemented in a superclass used by only one (or a few) subclasses?
SolutionMove this behavior to the subclasses.
At first a certain method was meant to be universal for all classes but in reality is used in only one subclass. This situation can occur when planned features fail to materialize.
Such situations can also occur after partial extraction (or removal) of functionality from a class hierarchy, leaving a method that is used in only one subclass.
If you see that a method is needed by more than one subclass, but not all of them, it may be useful to create an intermediate subclass and move the method to it. This allows avoiding the code duplication that would result from pushing a method down to all subclasses.
- Improves class coherence. A method is located where you expect to see it.
How to Refactor
Declare the method in a subclass and copy its code from the superclass.
Remove the method from the superclass.
Find all places where the method is used and verify that it is called from the necessary subclass.
Tired of reading?
No wonder, there are 7 hours worth of the text on this website.
Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.Learn more...