Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

2009-07-23

When to Introduce an Interface (in Java code)

TG 2009 - CC Euro setupThis 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.