I frequently come across projects that strictly define an interface for each and every class. 90% of those interfaces feature only a single implementation. Proponents of these "preemptive interfacs" defend this approach as follows:
- In Java one should always program to interfaces to minimize refactoring efforts, when an additional implementation is required.
- Testing is much easier with interfaces, since you can stub or mock objects easily.
- Frameworks, e.g. Spring make use of Java's proprietary Dynamic Proxies and therefore require interfaces.
While all of those points seem to have some merits, I think they don't justify the massive increase in number of classes the defining interfaces preemptively entails. Also:
- Factoring out interfaces once multiple implementation are required is a matter of seconds with contemporary IDEs.
- Mocking classes without interfaces is easy with Mockito or other Unit Testing Frameworks.
- Frameworks like Spring can use byte code generation libraries like CGLIB or Javaassist instead of Java's proprietary Dynamic Proxy mechanism.
Keeping all this in mind, is there really a compelling reason for "preemptive interface" definition or is it a relict of the past and could even be regarded an anti-pattern?
interface
s when Java didn't even exist yet when the book was written (and the quote is much older than the book, and thus much older than Java, anyway)? – Jörg W Mittag Jul 19 '16 at 11:57interface
construct in Java, which is simply impossible because Java didn't yet exist (at least publicly) when that book was written. Plus, it should be clear when you actually read the entire paragraph instead of just the bullet points that that's definitely … – Jörg W Mittag Jul 19 '16 at 23:12interface
and thinking that this act magically creates good OO design, as your colleague seems to do. – Jörg W Mittag Jul 19 '16 at 23:15