This week's book giveaway is in the Other Open Source APIs forum. We're giving away four copies of Storm Applied and have Sean Allen, Peter Pathirana & Matthew Jankowski on-line! See this thread for details.
I understand writing code to interfaces, but if interfaces become 1 interface to 1 concrete class, isn't that a bit overkill? I would prefer to keep the use of interfaces to only build one when they enforce a capability shared by multiple concrete classes. That being said, do you think an interface is really necessary when it is only implemented by 1 concrete class?
Yes even in these cases I would argue you still want to use interfaces here are a few reasons:
1) Provides a layer of abstraction useful for code reuse (Applies even for one implementation)
2) Can change the implementation or add more implementations in the future without affecting the code using the interface
3) Interfaces are much easier to test effectively (this one is especially important even with only once concrete class)
4) Allows you to use Springs interface based proxying (this also applies to the default proxying mechanism used by Spring even with only one concrete class)
5) Defines a clear contract that can be used. Helps with maintainability if the implementation changes. (You never know when things will change in the future when it does you will be glad you used an interface)
6) Polymorphism as well as many useful design patterns make heavy use of interfaces.
7) Has zero overhead and requires hardly any time to write. Most IDE's will generate it.
So even if there is at this time only one implementation, having that interface provides a few benefits with a potential for a huge savings in refactoring later when everything changes (like it always does).
Like anything I am sure we could find exceptions to the rule but I think it is a good general principal to get into the habit of doing.
Ok I'm convinced. I didn't get very far in that article to be convinced that even in minor cases (as you pointed out) there are benefits for using interfaces. The abstraction that it gives and the ability to more easily test are what sold me. We don't do much test first or test driven development on the projects that I've been on, but if we had I can see how always using interfaces would have helped us.