Refactoring Extract Interface
ProblemMultiple clients are using the same part of a class interface. Another case: part of the interface in two classes is the same.
SolutionMove this identical portion to its own interface.
Interfaces are very apropos when classes play special roles in different situations. Use Extract Interface to explicitly indicate which role.
Another convenient case arises when you need to describe the operations that a class performs on its server. If it is planned to eventually allow use of servers of multiple types, all servers must implement the interface.
Good to Know
Extracting an interface allows isolating only common interfaces, not common code. In other words, if classes contain Duplicate Code, extracting the interface will not help you to deduplicate.
All the same, this problem can be mitigated by applying Extract Class to move the behavior that contains the duplication to a separate component and delegating all the work to it. If the common behavior is large in size, you can always use Extract Superclass. This is even easier, of course, but remember that if you take this path you will get only one parent class.
How to Refactor
Create an empty interface.
Declare common operations in the interface.
Declare the necessary classes as implementing the interface.
Change type declarations in the client code to use the new interface.
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 ()