4 ms·
I think the bulk of this post is speaking to the interface segregation principle. Also, I would not use the advice below as a _blanket rule_ as the author puts
by TravHatesMe 7y ago
I think the bulk of this post is speaking to the interface segregation principle.
Also, I would not use the advice below as a _blanket rule_ as the author puts it.
> interfaces generally belong in the package that uses values of the interface type, not the package that implements those values.
It could be a good rule for many applications, but I find it difficult to swallow as a universal rule. I feel there is so many possibilities where this might not apply, for example perhaps you have a module comprised entirely of interfaces in order to decouple a layer of implementation.
- kubanczyk 7y agoToo bad author forgot to mention the tradeoff. This pattern violates DRY the hard way. I think most seen example is Go, where stdlib has no "http.Client" interface but only a struct. So every implementation of http client at some point gets the same copy-pasted code for the interface, so it could use it for that pattern of mocking. I'm not saying it's bad - I'm also doing it. It's just a design decision.
- Thorrez 7y agoIf that interface was in the http package, that would be a problem. Let's say they want to add a new method to http.Client . Would they add that to the interface? If no, then it would be difficult to test code that uses that new method. If yes, then all existing mocking code will stop compiling, because those mocks will no longer implement that interface.
- capableweb 7y ago> but I find it difficult to swallow as a universal rule But the author doesn't claim it's a universal rule, the author claims that the rule applies generally. Good thing to think about the cases it doesn't apply, but the author did put it in a proper way to express this.
- tsimionescu 7y agoTo me the case described in the article is actually one of the rarer uses of interfaces: you're the only one using a handful of methods from a single class which has many more. If you're using all/most methods of the class, you'd be better off if the interface was defined directly by the class. If there are many different users of the same subset of methods, it's better if the class designer declares that interface. If there are multiple classes implementing the same interface, it's almost crucial that the implementers agree on and define the interface. So I would say, the statement should be 'in general, interfaces belong in the package that implements value of the interface type; but don't forget that sometimes they can be declared by the code that uses them'.