If you're using a language where classes must be hard-coded into the code (e.g. Java/C#) then it might make sense to use an interface in case you ever want to change the implementation of Behavior
that gets passed to ClientA
or ClientB
without recompiling. This usually happens when you want to unit test some code by providing mock implementations of Behavior
. Without an interface you'd have to change the import statement of the client code so that it references the right implementation and recompile it.
In languages that don't hard-code references to classes using globally-unique identifiers (which is what fully-qualified names such as com.yoursite.Foo are) this isn't an issue and there's no need to make an interface. However languages with this kind of module system are relatively unpopular functional languages (e.g. Standard ML, OCaml) so it likely doesn't apply to you.
Note, however, that not every class can be implemented as an interface. Consider:
public class LooksAtOthers {
public LooksAtOthers binaryOperation(LooksAtOthers other) {
...
}
}
The binary operation here looks at the private fields of other
. This comes up a lot when implementing data structures; in order to do efficient merges or unions you have to be able to look at the implementation of both operands. This can't be done from an interface:
public interface CantLook {
CantLook binaryOperation(CantLook other)
}
public class CantLookImpl implements CantLook {
public CantLook binaryOperation(CantLook other) {
// no idea what type CantLook has
}
}
Here CantLook
is an interface, so the class implementing CantLook has no idea what private fields other
has. As a result if binaryOperation
required looking inside other
, it can't be implemented efficiently any more.
Note also that using a class makes debugging somewhat easier. With a class any given client code only interacts with one implementation; it either works or it doesn't. With an interface there can be any number of implementations and nothing stops someone from making a bad one. If you use an interface and ClientA
breaks, you have to look at which implementation of Behavior
broke it. Someone might've created and passed in a buggy ImplementerC
.
So the bottom line is: it depends. Does it bother you to have to change import statements? Are you doing unit testing? Do you need to look at other instances of the class?
new ClientA(new ImplementationB())
is valid code that works, and yet breaks at runtime, then you have polymorphism, and it is being misused. Interfaces are not just categorising, they are abstracting over behaviour.