TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Ask HN: How do you feel about optional dependency injection?

4 点作者 sprain大约 10 年前
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 &quot;optional dependency injection&quot;.<p>I haven&#x27;t found anything about this approach so far. So I figured I&#x27;d ask you guys how you feel about it. Would you consider this good or bad?<p>Example in PHP:<p><pre><code> public function __construct(Cache $cache = null) { $this-&gt;cache = $cache; &#x2F;&#x2F; Create default cache if none has been provided if (null == $this-&gt;cache) { $this-&gt;cache = new SomeCache(); } }</code></pre>

3 条评论

Terr_大约 10 年前
If it&#x27;s possible in your particular language&#x2F;framework, I would instead use setter-injection, and reserve constructor parameters for things the object truly needs access to before it can exist. In other words, let your design be guided by some of the basic principles you&#x27;d follow if you didn&#x27;t have a dependency-injection system at all.<p>Assuming 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&#x27;re predicting that most of the time a cache will not be wanted.<p>If it were the other way around, I would instead make it a <i>required</i> parameter, and provide a convenient dummy&#x2F;no-op Cache implementation people could use.
评论 #9196023 未加载
bartonfink大约 10 年前
I&#x27;ve written this exact idiom in some parts of a very poorly structured, tightly-coupled PHP codebase I&#x27;ve inherited. I&#x27;m not a huge fan, because it clutters the codebase a bit (that&#x27;s 4 lines of overhead per dependency), but in the absence of a true DI framework this is better than nothing. You get many of the functional benefits of DI, but not all of the niceties when it comes to cleaning up your code.
xrstf大约 10 年前
I personally would put this fallback logic into a Factory class&#x2F;method and make the $cache parameter required for the constructor. I like to keep my constructors as simple and cheap as possible and usually have some sort of factory code somewhere anyway.