This is an answer to a question asked at Java Ranch: "How often should classes be programmed to an interface?" As this question gets asked regularly, I thought I'd "archive" it here...
I basically introduce an interface for five different reasons:
- I want to mock an object for a unit test
- a client only needs to depend on a small subset of the operations of a class (and for some reason, I can't/won't break down the class into smaller ones) (Interface Segregation Principle)
- to invert the dependency between two modules (Dependency Inversion Principle)
- to use polymorphism with classes that aren't related by a common superclass
- I need to publish an API to a third party
In all other cases, I find that with modern tools it's so easy to introduce an interface after the fact - once I feel the need for it -, that introducing it "just in case" creates more disadvantages than advantages.
The java.io.Closeable interface is a perfect example for allowing polymorphism: I can write a method that can close both an InputStream, an OutputStream, a Reader and a Writer, even though they don't share a common base class. (That wasn't possible before Java 1.5, where the interface was introduced.) Does that help?





