Search code examples
javaoopdesign-principles

(Programming to an interface v/s working with concrete class) when there is just one concrete class


In an OO component, when you have only one implementation available for an class and that class is not 'published' to other components, is it still advisable to have an interface and work with the interface instead?

I am fully aware of 'programming to an interface' design principle and also use it extensively.

Lately, I have been observing that most of the time a different implementation (although possible and would make sense) is never needed. As a result of always working with interfaces, the application code would have a fair amount of interfaces with just one implementation for each and the interface seems sort of an overhead.

Instead, is it preferable to just work with the concrete class and introduce the interface only when a second implementation is needed? Anyway, nowadays extracting an interface using IDEs is a breeze. And when the new interface is introduced, references to the old concrete class can be changed to use the new interface instead.

What do you think?


Solution

  • To my knowledge, there are three situations where an interface is justified:

    1. It's part of the architecture (I admit this one isn't very well defined).
    2. You have more than 1 implementation.
    3. It's a public interface.

    Don't be afraid to use concrete classes. Don't mechanically generate an interface for every single class.