D — Dependency Inversion & Dependency Injection
Definition
Dependency Inversion Principle
- In plain English
- The Dependency Inversion Principle says business code should depend on interfaces it defines, not on concrete details like databases or email services.
- Think of it like
- It is like a lamp built for a standard wall socket instead of wired straight into one power station.
Dependency injection
- In plain English
- Dependency injection means handing a type the things it needs from outside, usually through its constructor, instead of letting it create them itself.
- Think of it like
- It is like a chef who is handed ingredients by the kitchen instead of driving to the farm each morning.
Why it exists
Your scheduler opens its own database connection. Testing one scheduling rule now requires a running database.
Changing that database also means editing scheduling code. Let the scheduler state its needs, then pass in the chosen storage.
Injection supplies the parts. Inversion decides that business code depends on its own interfaces; you can inject a concrete type without that separation.
How it works
High-level and low-level code
- In plain English
- High-level code holds the business rules, while low-level code handles details such as databases, files and networks.
- Think of it like
- Like a recipe versus the brand of oven.
package scheduler
type Postgres struct{}
func openPostgres() *Postgres { return &Postgres{} }
func (*Postgres) Slots() int { return 4 }
type Scheduler struct{ db *Postgres }
func NewScheduler() *Scheduler { return &Scheduler{db: openPostgres()} }
func (s *Scheduler) Available() bool { return s.db.Slots() > 0 }
package main
import "fmt"
type SlotStore interface{ Slots() int }
type Scheduler struct{ store SlotStore }
func NewScheduler(store SlotStore) *Scheduler { return &Scheduler{store: store} }
func (s *Scheduler) Available() bool { return s.store.Slots() > 0 }
type PostgresStore struct{}
func (PostgresStore) Slots() int { return 4 }
func main() { fmt.Println(NewScheduler(PostgresStore{}).Available()) }
Composition root
- In plain English
- The composition root is the one place, usually main, where you create the real parts and plug them together.
- Think of it like
- Like a stage manager placing every prop before the play starts.
Before, Scheduler points to Postgres. After, Scheduler uses SlotStore, and PostgresStore satisfies that scheduler-owned interface.
Dependency injection in Go usually uses ordinary constructor parameters. No extra framework is required.
Examples
Replace live positions with recorded input
ArrivalPredictor reads a bus position. A recorded position lets you test the same estimate repeatedly.
package main
import "fmt"
type LiveGPS struct{}
func (LiveGPS) RemainingStops() int { return 3 }
type ArrivalPredictor struct{ gps LiveGPS }
func NewArrivalPredictor() ArrivalPredictor { return ArrivalPredictor{LiveGPS{}} }
func (p ArrivalPredictor) Minutes() int { return p.gps.RemainingStops() * 2 }
func main() { fmt.Println(NewArrivalPredictor().Minutes()) }
package main
import "fmt"
type PositionFeed interface{ RemainingStops() int }
type ArrivalPredictor struct{ feed PositionFeed }
func NewArrivalPredictor(feed PositionFeed) ArrivalPredictor { return ArrivalPredictor{feed} }
func (p ArrivalPredictor) Minutes() int { return p.feed.RemainingStops() * 2 }
type RecordedPosition struct{ Stops int }
func (r RecordedPosition) RemainingStops() int { return r.Stops }
func main() { fmt.Println(NewArrivalPredictor(RecordedPosition{3}).Minutes()) }
The insight
Injected inputs make location logic testable.
Choose payment providers in main
Checkout creates a payment provider itself. You want to switch providers without changing the checkout rule.
package main
import "fmt"
type ProviderA struct{}
func (ProviderA) Pay(cents int) error {
fmt.Println("A paid", cents)
return nil
}
type Checkout struct{ gateway ProviderA }
func NewCheckout() Checkout { return Checkout{ProviderA{}} }
func (c Checkout) Buy(cents int) error { return c.gateway.Pay(cents) }
func main() { fmt.Println(NewCheckout().Buy(2500)) }
package main
import "fmt"
type PaymentGateway interface{ Pay(int) error }
type Checkout struct{ gateway PaymentGateway }
func NewCheckout(g PaymentGateway) Checkout { return Checkout{g} }
func (c Checkout) Buy(cents int) error { return c.gateway.Pay(cents) }
type ProviderB struct{}
func (ProviderB) Pay(cents int) error {
fmt.Println("B paid", cents)
return nil
}
func main() { fmt.Println(NewCheckout(ProviderB{}).Buy(2500)) }
The insight
Details change at the edge, while the business rule keeps its interface.
Move the clock forward in a test
The review scheduler reads the current time directly. You need to check tomorrow's due cards without waiting or changing the computer's clock.
package main
import (
"fmt"
"time"
)
type Scheduler struct{}
func (Scheduler) Due(at time.Time) bool { return !time.Now().Before(at) }
func main() {
tomorrow := time.Date(2030, 1, 2, 9, 0, 0, 0, time.UTC)
fmt.Println((Scheduler{}).Due(tomorrow))
}
package main
import (
"fmt"
"time"
)
type Clock interface{ Now() time.Time }
type Scheduler struct{ clock Clock }
func NewScheduler(c Clock) Scheduler { return Scheduler{c} }
func (s Scheduler) Due(at time.Time) bool { return !s.clock.Now().Before(at) }
type FixedClock struct{ At time.Time }
func (c FixedClock) Now() time.Time { return c.At }
func main() {
tomorrow := time.Date(2030, 1, 2, 9, 0, 0, 0, time.UTC)
s := NewScheduler(FixedClock{tomorrow})
fmt.Println(s.Due(tomorrow))
}
FixedClock always returns the chosen instant. The example treats a card as due at its exact scheduled time.
The insight
Time is also a dependency you can pass in.
Trade-offs
Pros
- Test rules with controlled inputs.
- Swap external details.
- Keep business rules focused.
Cons
- More interfaces and setup code.
- Passing tiny helpers adds noise.
Use when
- Inputs come from databases or networks.
- Time or random values make results unpredictable.
Avoid when
- A helper already returns predictable results from its inputs.
- Passing strings.ToUpper would add no useful control.
Quick check
Takeaways
- Business code owns the interfaces; details satisfy them.
- Pass dependencies in through constructors.
- Wire the real parts once, in main.