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.

4 comments:

  1. In regard to the first one, would you still do it you could easily mock a concrete class? In C# (I don't know how it is in Java) there's commercial mocking tools that let you mock concrete classes, but there are no open source variants that let you do that.

    It boils down to this: would you design the software differently if you didn't have to take particular steps (like introducing interfaces) if you could test it just as easily?

    ReplyDelete
  2. Hi Knut,

    we recently switched to Mockito, which allows to mock concrete classes in Java.

    It still feels kinda icky to me to mock a concrete class - like a design smell. I can't really put my finger on it yet, though. Time will tell whether that's something I just need get over, or whether there is some deeper design insight waiting there...

    ReplyDelete
  3. I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here. 3PL eCommerce Fulfillment

    ReplyDelete

Thank you for your comment!