System Design Academy

Saving…

Lesson 6 of 7 in Module 20 of 45 lessons complete

D — Dependency Inversion & Dependency Injection

Module 2, lesson 6Concept12 min

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.
Before: scheduler creates a concrete store; database access is represented by a stand-in.
Go
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 }
After: scheduler owns SlotStore; main connects a stand-in store.
Go
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.

The detail now depends on a promise owned by the business code.

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.

Before: estimate arrival at two minutes per remaining stop; live GPS is a stand-in.
Go
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()) }
After: estimate arrival at two minutes per remaining stop; live GPS is a stand-in.
Go
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.

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

Your business code calls time.Now() directly, so testing "due tomorrow" means waiting a day. Best fix?
In Go, dependency injection most commonly means…

Takeaways

  • Business code owns the interfaces; details satisfy them.
  • Pass dependencies in through constructors.
  • Wire the real parts once, in main.

Try the quick check above whenever you feel ready.

Previous: I — Interface Segregation Principle