Under what conditions is it valid to use Field injection instead of Constructor injection? [closed]

StackOverflow https://stackoverflow.com/questions/21935965

質問

I am using GUICE as a Dependency injection container. If I have an option to go for either Constructor injection or Field injection, I believe that I should always prefer Constructor injection over field injection. Is my understanding correct?

Are there any valid use cases where Field injection would make more sense than Constructor injection?

役に立ちましたか?

解決

Yes, you're correct. Try to avoid field injection when possible.

The most important thing, I believe, is when you use constructor injection, you can be absolutely sure that your objects will never be in inconsistent state, because you cannot create such object without creating its dependencies first. Also dependencies declared in constructor present clear contract for your class - you can easily see what that class depends on. This is not always true with field injection.

Moreover, you can use such objects without DI frameworks, for example, in unit tests. With field injection, on the contrary (especially when fields are private) you can't use your classes outside of DI container without excessive hassle. Your fields also can't be final if you employ field injection and want portability, and that's bad because you should try to make objects as immutable as possible.

Field injections are almost never needed. They are only good for optional dependencies (and even for these I suggest using method injection instead) or for special "aspect"-like dependencies, for example, loggers.

Another highly arguable use case is when you need create a class which has several superclasses, each having dependencies. With constructor injection you will have to pass all dependencies for all your superclasses through all constructors up to the top. This may be inconvenient, and field injection solves this. But this is a very rare use case (I've only encountered it in my practice once), and I personally think that passing dependencies through multiple constructors is not that bad.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top