Refactoring Collapse Hierarchy
ProblemYou have a class hierarchy in which a subclass is practically the same as its superclass.
SolutionMerge the subclass and superclass.
Your program has grown over time and a subclass and superclass have become practically the same. A feature was removed from a subclass, a method was moved to the superclass... and now you have two look-alike classes.
Program complexity is reduced. Fewer classes mean fewer things to keep straight in your head and fewer breakable moving parts to worry about during future code changes.
Navigating through your code is easier when methods are defined in one class early. You do not need to comb through the entire hierarchy to find a particular method.
When Not to Use
Does the class hierarchy that you are refactoring have more than one subclass? If so, after refactoring is complete, the remaining subclasses should become the inheritors of the class in which the hierarchy was collapsed.
But keep in mind that this can lead to violations of the Liskov substitution principle. For example, if your program emulates city transport networks and you accidentally collapse the
Transportsuperclass into the
Carsubclass, then the
Planeclass may become the inheritor of
How to Refactor
Select which class is easier to remove: the superclass or its subclass.
Replace all uses of the class that you are deleting with the class to which the fields and methods are to be migrated. Often this will be code for creating classes, variable and parameter typing, and documentation in code comments.
Delete the empty class.
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...