Faram
Faram

Reputation: 555

Handling dependency injections

let's say I have following code:

import (
   handlerA "some/path/handlerA"
   handlerB "some/path/handlerB"
   handlerC "some/path/handlerC"
   handlerD "some/path/handlerD"
   ....
   handlerZ "some/path/handlerZ"
)

func DoSomething(a handlerA.A, b handlerB.B, c handlerC.C, d handlerD.D..., z handlerZ.Z) {
   a.DoA()
   b.DoB()
   c.DoC()
   d.DoD()
   ....
   z.DoZ()
}

I obviously made the function DoSomething(...) mockable, as this makes my function unit testable. But because of that I get way to many arguments because of all the dependencies my function needs to get injected.

Is there a better way in Golang to handle many dependencies?

Upvotes: 0

Views: 90

Answers (1)

Faram
Faram

Reputation: 555

One way to handle many injections would be to use a struct as wrapper:

type SomethingDoer struct {
  a handlerA.A,
  b handlerB.B,
  c handlerC.C,
  d handlerD.D,
  ...
  z handlerZ.Z,
}

func (sd SomethingDoer) DoSomething() {
   sd.a.DoA()
   sd.b.DoB()
   sd.c.DoC()
   sd.d.DoD()
   ....
   sd.z.DoZ()
}

I just figured that out by reading the question by myself again...

Upvotes: 2

Related Questions