开发者

Dependency Injection: should dependent objects passed as constructor args or not?

On the video here http://code.google开发者_StackOverflow社区.com/p/google-guice/

It explains that it should.

And here OscarRyz says the contrary How to explain dependency injection to a 5-year-old?

So I'm confused now.


I personally prefer to use the fact that Constructors can naturally define all the mandatory fields and those fields which once set cannot be changed. You can do the same with setters but there is no direct language support for this.

While I prefer using constructors for mandatory and final fields, I don't see this as something specific to dependency injection.


There is no simple answer. It depends on the situation. Check section "Constructor versus Setter Injection" in Martin Fowler's article:

http://www.martinfowler.com/articles/injection.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜