4 ms·
Author here. > Does this not work? It works However, this is what I have recently found quite a lot. An interface is defined: type Foo interface {
by chewxy 9y ago
Author here.
> Does this not work?
It works
However, this is what I have recently found quite a lot. An interface is defined:
type Foo interface {
Method1()
unexportedMethod()
}
And in the same package, only one type (usually unexported) implements the interface. And the functions declared in the package typically take the concrete type instead of the interface type.
This is typical when developers come from Java and they do `abstract class Fooer` and immediately do `class Foo implements Fooer` within the same package. This is an anti pattern in Go.
> This seems like some arbitrary rule that the creators of Go claimed was a good idea, I guess
No. I think I was unclear. I specifically mention that it's not a great idea. It's a code smell. Instead, interfaces should be defined at point-of-use.
- freyir 9y agoWhat's the point of exporting the Foo interface if other packages cannot create or use Foo values?
- keypusher 9y ago> I specifically mention that it's not a great idea. It's a code smell. Instead, interfaces should be defined at point-of-use. You still have not said WHY it's not a great idea, or what the benefits of defining the interfaces at point-of-use are.
- chewxy 9y agoThe benefits of defining interfaces at point of use is decoupling of dependencies. Imagine you have two packages: A and B. A defines interface Fooer and struct FooThing. Package B only requires anything that can call Foo(). But because the interface is defined at A, now B is forever tied to A. When you change something in A, you have to worry if it changes something in B as well. If instead the interface Fooer is defined in B, package A can change as much as it likes without B needing to change.