samedi 3 juin 2023

Classic circular dependency problem I run into with interfaces in golang, what is the idiomatic way to resolve this?

So I have,

package A

type a struct {}

func New() *a {
  return &a{}
}

func (A *a) Boo() {}
package B

type a interface {
  Boo()
}

type b struct {}

func New() *b {
  return &a{}
}

func (B *b) Foo(A a) {} // Dependency injection
package driver

type driver struct {
  // in here I want to have a field which has the method Foo(B b)
}

The problem is that I cannot define an interface with method Foo(B b) as b is an unexported interface in package B. If I make it exported it leads to circular dependency.

What is the idiomatic way to handle this problem in golang?

Of course I can export the struct B and directly use it in driver package but if possible I would like to use interfaces for better testability. Am I overengineering?

Aucun commentaire:

Enregistrer un commentaire