Ask HN: How do you feel about optional dependency injection?
Often when writing a library I feel the need to make things simpler for quick and small projects and provide a way to skip verbose dependency injection for non-optional dependencies. I do this by using a non-injected default instance if no other dependency has been provided. I started calling this "optional dependency injection".
I haven't found anything about this approach so far. So I figured I'd ask you guys how you feel about it. Would you consider this good or bad?
Example in PHP:
public function __construct(Cache $cache = null)
{
$this->cache = $cache;
// Create default cache if none has been provided
if (null == $this->cache) {
$this->cache = new SomeCache();
}
}
7 comments
[ 4.6 ms ] story [ 31.0 ms ] threadAssuming constructor-injection is your only choice (or the only choice you can use autowiring for)... then this technique depends on making the correct guess about how people will use the object. In this case, you're predicting that most of the time a cache will not be wanted.
If it were the other way around, I would instead make it a required parameter, and provide a convenient dummy/no-op Cache implementation people could use.
To what extent is it important to make sure the person wiring things up knows and approves of what SomeCache does?
Maybe cache is a bad example. It could also be a HTTP client to fetch some data over an api. Let's say the library by default uses Guzzle. But if a user for some reason wants to inject his own implementation of Guzzle or even BuzzBrowser (which is compatible for basic operations) instead, he can.
For most simple projects, especially without a framework, the default implementation does the job and would save you some code.