Interfaces are used in Java to define the contract that an implementing class is bound to perform. In it’s essence, that is abstraction. The developer using the interface doesn’t need to be aware of the implementation. Unfortunately, lots of developers make the same mistake with interfaces as they do with design patterns. They see them as something to use for everything. It is my contention, that using an interface is a solution to the problem. If you have the problem, then you use them for abstraction. If you don’t have the problem, then you don’t use them. In this case, the problem that interfaces would be used to solve is the problem of having multiple implementations. If there are multiple implementations, it is helpful for the developer coding to the library to have one interface to code to, that can abstract away the peculiar details that are related to the specific implementations. Then the developer can be given the choice to change the implementation without having to re-code to the new implementation. The developer can code to the interface and that code can support multiple implementations without making a change. That is a very good use of in interface for the purpose of abstraction.
With that being said, I have been said to be anti-interface for a long while. It’s not that I’m against interfaces. I’m more against their abuse. If I have one implementation, then why would I need a interface to form a contract that the implementation must follow. Of course it follows it, it is the very definition. My problem with using an interface when there is only one implementation is that the problem of having to enforce the external interface doesn’t exist when there is only one implementation. There is no need for abstraction. To state it another way, interfaces are intended for developers of an API. If you are coding a solution to your problem, you are rarely if ever coding an API. You are coding a solution. I never worked on a project that received the benefit. Every time I worked on a project that used interfaces, the only benefit I received was double maintenance. Any time I changed the implementation class, it necessitated a change in the interface. I even used them with the idea that we are using JDBC now, but soon-enough, we are going to be using Hibernate. Doh. By the time we moved, the code was gutted so much to be unrecognizable. Thanks a lot.
I can see where they are useful in some cases, just not anything that I am working on.
Adam Bien’s Weblog has a post that contains some nice nuggets of information. When are interfaces a good idea. He states.
Very nice and straight to the point.
sheltonn February 22nd, 2011