Refactoring Extract Superclass
ProblemYou have two classes with common fields and methods.
SolutionCreate a shared superclass for them and move all the identical fields and methods to it.
One type of code duplication occurs when two classes perform similar tasks in the same way, or perform similar tasks in different ways. Objects offer a built-in mechanism for simplifying such situations via inheritance. But oftentimes this similarity remains unnoticed until classes are created, necessitating that an inheritance structure be created later.
- Code deduplication. Common fields and methods now "live" in one place only.
When Not to Use
- You can not apply this technique to classes that already have a superclass.
How to Refactor
Create an abstract superclass.
Use Pull Up Field, Pull Up Method, and Pull Up Constructor Body to move the common functionality to a superclass. Start with the fields, since in addition to the common fields you will need to move the fields that are used in the common methods.
Look for places in the client code where use of subclasses can be replaced with your new class (such as in type declarations).
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...
Everything is quite simple. This example is like video (but much cooler):
- After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
- You can fast-forward or return to previous steps by pressing arrow buttons on the left.
- Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
- To check the code for errors, you can press "Compile and test" button ()