4 ms·
Having an interface for a single implementation is just redundant. A class already has an interface - it's public API. Other than that I agree, most "best prac
by oweiler 5y ago
Having an interface for a single implementation is just redundant. A class already has an interface - it's public API.
Other than that I agree, most "best practices" are subjective and boil down to personal preference.
- josteink 5y ago> Having an interface for a single implementation is just redundant. A class already has an interface - it's public API. Depends on the language. And sometimes you want to enforce a public contract of any implementation (current and future). Personally for me, the biggest gain I see when writing against interfaces is that any class which expects a interface is already prepared for test-doubles, as opposed to classes written against concrete implementations which may even be initialised internally. Then just even starting to write a test becomes a so much bigger task. Of course, everything with moderation, sometimes even moderation itself ;)
- jayd16 5y agoI usually agree but sometimes you want to reduce the exposure of the public methods of the concrete class even if there's only one concrete implementer. For example, you might want to pass around a class and only expose the getters and not the setters.
- BadOakOx 5y agoHaving an interface let's you introduce versions or alternative implementations easily, this is important in a long run. It's much easier to handle the transitions, because you can have both versions in your code base and you can easily switch back to the old one if necessary. When you start with a class and you want to do similar thing, you either YOLO it and change everything at once, or you need to introduce an interface and replace every usage to use the interface to achieve a safer transition and you are back at the interface-class implementation with an extra pain.
- Jtsummers 5y agoInterfaces serve two roles: 1. They are (usually) concise specification/contract for the implementation to follow, and for the client to use. 2. They permit substitution. These are, from my experience, the principle and most useful reasons to make use of "redundant" interface definitions. What's worse is when people want alternative implementations but only have a concrete instance, they subclass it and break all kinds of contracts making their square peg fit a round hole. This is less useful when you have ducktyping and consequently every lookalike is considered substitutable for each other.
- floverfelt 5y agoI feel like the responses to this comment are somewhat proving the point around most things being preference. ;)