Chapter 11: Design

Some of what makes code hard to change is what it reaches out and grabs for itself.

Dependency injection

Also called DI

Passing a function the things it needs, so it doesn't have to go and get them. isExpired(token, now) can be tested at any date. A function that reads the real clock inside can only be tested today.

Code that reaches for the real clock, network or database leaves an agent two choices: mock everything or skip the test. With injection, the honest test is also the easy one, so that is the one you tend to get.

Say it to your agent

“isExpired reads Date.now() inside, so the test can't control time. Add a now parameter that defaults to Date.now(), and add tests for one second before and one second after expiry.”

The workshop

Name a word, or describe what you mean in everyday language.