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?
Interfaces cannot have any concrete methods. If you need the ability to have abstract method definitions and concrete methods then you should use an abstract class.
A concrete class can implement multiple interfaces, but can only inherit from one parent class.
All the methods in an interface must be abstract, you cannot have a concrete method (the one which has body) if you try to do so, it gives you a compile time error saying “interface abstract methods cannot have body”.
Interface is a blueprint for your class that can be used to implement a class ( abstract or not); the point is interface cannot have any concrete methods. Concrete methods are those methods which have some code inside them; in one word - implemented. What your interface can have is static members and method signatures.
One reason I continue to program to an interface even with only one implementation is because it makes writing my tests a lot easier. I can set up proxies to test whatever I want to test and I don't have to worry about tight coupling.
This isn't always going to be advisable, but it's something worth thinking about when you're trying to decide. Do you think you'll need to extensively test around this class/object? If you think you will be it can be a lot easier dealing with the interface as opposed to the concrete class.
The alternative to that would be to not use the interface and subclass the concrete class, which works too, but again it depends.
Creating interfaces for concrete types is a delicate balancing act as you can easily create an interface explosion that provides no benefit and only complicates the domain space with redundant types.
My rule of thumb is to only create interfaces for types that are part of a public-facing API. All types that are dedicated to the implementation of the API and are never exposed from the API don't need an interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With