Track 04 · Lesson 7 of 15Code that stays easy to change

Track 04 · Code that stays easy to change

D: Dependency inversion

Lesson 7 of 15· 7 min

Important logic shouldn’t depend on details like a specific email provider, database or clock. Both should depend on a small interface instead, and the details get plugged in from outside. It’s the D in SOLID, and the one that makes code testable.

Run the sign-up tests

Run them, switch providers, then flip the switch

signUp() sends a welcome email and sets a 14-day trial.

new SendGridClient(…) and new Date() are hard-wired inside signUp()

0

Real customers emailed by tests

–

Files to edit to switch provider

The business rule is welded to one email company and to today’s date.

signup.tsWithout it
import { SendGridClient } from "@sendgrid/mail"

export async function signUp(email: string) {
  const user = await db.users.create({ email })
  const trialEnds = new Date()                 // the real clock
  trialEnds.setDate(trialEnds.getDate() + 14)

  // A concrete provider, wired in right here
  await new SendGridClient(process.env.SENDGRID_KEY!).send({
    to: email,
    subject: `Your trial ends ${trialEnds.toDateString()}`,
  })
  return user
}

// The test sends a real email and depends on today's date.

Invert the arrow#

Without the principle, signUp reaches out and grabs SendGrid and new Date(): the business rule depends on the details. With it, signUp declares what it needs (a Mailer, a Clock) and receives them. The details now depend on the interface the business rule owns, so the arrow points the other way.

Wire it in one place#

Somewhere near the entry point (main.ts, a server setup file, a React provider) one piece of code picks the real implementations. Tests pass fakes; local development can pass a console mailer. Nothing else in the codebase knows which provider you use, so switching is one line.

Don’t wrap everything#

Depend on interfaces at the edges that really vary or are hard to test: email, payments, time, randomness, the network, storage. Wrapping the standard library or a pure helper adds indirection for nothing.

Check yourself

Why does dependency inversion make code easier to test?