Why should dependencies be injected?
Code should not instantiate or otherwise access its own dependencies. Instead, prefer to pass in dependencies as arguments.
This should be done when code becomes important enough to unit test. Dependency injection makes it easier for tests to provide dependencies with different configurations. It also makes it easier to inspect the side effects introduced onto dependencies. It will also make maintenance easier because it will increase flexibility at little cost.
When working with I/O, pass in interfaces instead of instantiating classes
// Avoid new()ing the dependency
public function getDatabaseConnectionInfo(): ConnectionInfo {
$redis = new Redis();
return new ConnectionInfo(
$redis->get('host'),
$redis->get('port')
);
}
// Prefer to pass the dependency in
public function getDatabaseConnectionInfo(
Redis $redis
): ConnectionInfo {
return new ConnectionInfo(
$redis->get('host'),
$redis->get('port')
);
}
// Passing in an interface is even better
public function getDatabaseConnectionInfo(
KeyValueInterface $key_value_store
): ConnectionInfo {
return new ConnectionInfo(
$key_value_store->get('host'),
$key_value_store->get('port')
);
}
Dependency injection makes testing easier.
The unit test can take a trivial in-memory store instead of either wrangling a Redis instance or mocking a constructor.
Additionally, code that manages its own dependencies can become nested deep within other code. If the first example above became deeply nested, it would be unclear that the corresponding test must manage a key/value store. This could lead to bad surprises like tests attempting to connect to Redis.
Dependency injection increases flexibility at little cost.
In the example above, it may become necessary to introduce a caching layer in front of the key/value store. This is easy with dependency injection. Just make a new class that inherits the interface and delegates to the I/O layer on cache misses. Without dependency injection, it becomes a project to find and fix all usages.
Dependency injection makes it easier to make application-wide changes.
In the above example, it may become necessary to stop using the default Redis database and configure which Redis database should be used. If the Redis class is instantiated in many places, this becomes a sizable effort. Compare this to changing the single invocation that is injected throughout the application. The latter will usually be much easier.
Pass the result of I/O into business and presentation logic
// Avoid performing I/O in business logic
public function isShopTemporarilyClosed(
ORM $orm, int $shop_id
): bool {
// All shops manually turned off by the owner
// are called temporarily closed.
$shop = $orm->getFinder('Shop')->findById($shop_id);
return $shop->is_off
&& $shop->owner->id === $shop->disabled_by_user->id;
}
// Prefer passing the result of I/O into business logic
public function isShopTemporarilyClosed(
Shop $shop
): bool {
// All shops manually turned off by the owner
// are called temporarily closed.
return $shop->is_off
&& $shop->owner->id === $shop->disabled_by_user->id;
}
Business/presentation logic should not be overly opinionated
Applications often have several choices about where they can read equivalent data. This function shouldn’t care that the data came from the ORM. Why couldn’t it be passed in the POST data of a request? Or be fetched from a REST API? Ideally, logic that acts on a shop model should work anywhere.
Doing I/O in application logic makes its callers difficult to refactor
As a codebase grows, helper functions may acquire dozens or hundreds or thousands of callsites. They may become nested deep within the application call stack. It will be used within business-critical logic that will run into scaling problems. Manually managing dependencies makes it difficult to perform some optimizations. For example, it’s difficult to ensure that the program never makes redundant I/O calls when the object is accessed via I/O dozens of times in a codebase. This is true even with caching! It’s often the case that calling two different I/O entry points (or the same entry point with different arguments) can produce the same results. This can be difficult or impossible to programmatically detect, even though it may be obvious to the application developer.
Passing in the result of I/O makes it easier to share the result of I/O among different callers.
I/O introduces nondeterministic behavior
It would be surprising to see a DatabaseReadException when calculating whether a shop is closed. But introducing I/O into a call increases the risk that code can throw exceptions for nondeterministic reasons like service availability.
I/O also dramatically affects timing metrics. Let’s say that I/O calls are cached, and the shop is fetched in two places: once while deciding which views to render, and once while rendering the view. Later, a programmer realizes that they don’t need to perform the first fetch. They remove it. This will move the I/O call from the application logic into the view logic, causing the view logic’s timing instrumentation to increase. This is because a former cache hit is now a cache miss with I/O fetching. No regression happened, but the application performance graphs make it seem like one did.
This could also cause tests to become flaky if they actually perform the I/O and sometimes fail.
Instead, prefer to centralize or share logic related to I/O. The details of this will depend on which languages and libraries are used.
Don’t access static or global state within business or presentation logic
// Avoid accessing global or static state in business logic
public function isLocaleEnUs(): bool {
return strtolower($_REQUEST('locale')) === 'en-us';
}
// Pass global or static state into business logic
public function isLocaleEnUs(string $locale): bool {
return strtolower($locale) === 'en-us';
}
Accessing static and global state is unsafe across machines
A helper that access static or global state makes strong assumptions about what happened on the machine prior to the code executing. Note: this refers to static state – the reliance on information from the execution environment, or calculated data that is stored statically. Accessing static data or static functions isn’t included in this.
If code lives long enough, it will eventually execute in several layers of the same application stack. Think about all the different application architectures that can exist in the same company at the same time. Reverse proxies in front of long-lived application servers, CGI scripts, batch processing jobs, monoliths, microservices, single-page applications, mobile apps, serverless lambdas, server-side rendering, etc. And to add another dimension, there are quite a few transport mechanisms available: HTTP, RPC, IPC, etc.
As code becomes longer-lived, it will eventually live within several layers at the same time. This introduces unnecessary complexity on each of the additional layers. If some logic directly reads the request parameters to determine the locale, that it (and every thing that ever depends on it) will always need to execute within an HTTP request. Or it must fake the HTTP request environment when it is included in a layer without HTTP. Or if it’s proxied within HTTP, the proxied call will also need to forward the request parameters, even if it doesn’t make semantic sense.
How to move an existing codebase towards dependency injection
This can be done incrementally. For each commit that uses a dependency, refactor that dependency to come from one layer higher in the stack. This is a good opportunity to introduce tests for untested code, or simplify tests for existing code.
Over time, frequently-modified code will become fully implemented using dependency injection. It may be necessary to do a special project to modify, replace, or delete code that hasn’t been touched in years. But maybe it’s fine to just leave it. After all, it hasn’t been modified in years.