Track 04 · Lesson 7 of 15Code that stays easy to change
- 01Principles at a glance
- 02SOLID principles at a glance
- 03S: Single responsibility
- 04O: Open/closed
- 05L: Liskov substitution
- 06I: Interface segregation
- 07D: Dependency inversion
- 08Separation of concerns
- 09DRY: Don't repeat yourself
- 10KISS: Keep it simple
- 11YAGNI: You aren't gonna need it
- 12Composition over configuration
- 13Fail fast
- 14Least surprise
- 15When they disagree
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.
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