Extract Interface.
Problem
Multiple clients are using the same part of a class interface. Another case: part of the interface in two classes is the same.
Solution
Move this identical portion to its own interface.
##Example
Before
class Employee {
double getRate() { return rate; }
boolean hasSpecialSkill() { return special; }
}
class Timesheet {
double charge(Employee emp, int days) {
return emp.getRate() * days;
}
}After
interface Billable {
double getRate();
}
class Employee implements Billable {
public double getRate() { return rate; }
boolean hasSpecialSkill() { return special; }
}
class Timesheet {
double charge(Billable emp, int days) {
return emp.getRate() * days;
}
}##Why Refactor
-
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’s planned to eventually allow use of servers of multiple types, all servers must implement the interface.
##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.