user310291
user310291

Reputation: 38180

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

On the video here http://code.google.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.

Upvotes: 3

Views: 352

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533442

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.

Upvotes: 7

StanislawSwierc
StanislawSwierc

Reputation: 2591

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

Upvotes: 5

Related Questions