3 ms·
I'm curious what you mean by "necessary for proper testing". I know a lot of people use that pattern (single-implementation interfaces) for use with a dependenc
by ubertaco 7y ago
I'm curious what you mean by "necessary for proper testing". I know a lot of people use that pattern (single-implementation interfaces) for use with a dependency-injection container, and then they mock the interfaces...but that doesn't buy you any more than mocking the implementation classes themselves would.
In terms of when to split them out, my rule of thumb is "when there's more than one implementation class that does the same function".
Good examples are things like Comparable/Comparator, Reader, Writer, Serializable -- these are all descriptions of behavior for which multiple implementations exist. Interfaces, in general, are adjectives (or at least adjective-ish).
Bad examples are things like CheckoutService, ShoppingCartManager, JwtTokenManager -- these are all descriptions of specific components within an application that have a single implementation. These are nouns, and generally they're a sort of "proper noun" (in that they refer to one single thing by its name). If you don't already have many implementations for the behavior they implement, then you don't need an interface (since an interface is just a way of describing a set of "external-facing" contracts which many specific implementations may fulfill -- like List vs LinkedList/ArrayList).
The reason why is simply that it's just waste. It's more code for more code's sake. At best, you're just clicking "go to definition" one extra time, and at worst your code is confusing (because someone might assume the presence of the interface means it's "swappable" behavior, rather than integral application logic).
The "YAGNI" ("You Aren't Going To Need It") principle applies here: if you don't know you're going to need it, don't build it. Once you do know that you're going to need it, then you build it. Anything before that point winds up being wasted time/effort.
- asdfman123 7y agoOh, so basically don't use interfaces unless you actually need the functionality provided by interfaces (namely, polymorphism). Got it!