开发者

Injecting direct object dependencies, or methods directly as well

开发者 https://www.devze.com 2023-03-02 15:41 出处:网络
A best practice in DI I\'ve read in a few places is not to inject object B just to get at object C, but to inject C instead.

A best practice in DI I've read in a few places is not to inject object B just to get at object C, but to inject C instead.

But if a single method from C is all that is required, would you just inject that method instead of C?

If so, what about if a few methods from C were required? Is there a point that it's just more convenient to pass in the full object and live with the fact that you're getting stuff you have no interest in?

Or does that point indicate that maybe class C has too many varied responsibilities an开发者_如何学运维d needs to be extracted into multiple smaller classes, the objects of which can then be injected without as much baggage?

Don't be afraid to state the obvious, this is all new to me.


If the dependency has (many) more methods than you care about, it's a pretty good sign that it's a Header Interface that violates the Interface Segregation Principle.

If you have control over the interface, I'd suggest splitting it up into several smaller Role Interfaces. You can still have one concrete class implementing more than one Role Interface if that makes more sense for your specific implementation.

If you don't control the design of the dependency, I'd tend towards injecting the whole interface, as it still represents a cohesive collection of behavior (even if we don't agree with the design choice of the original designer). You might need more of that behavior later on.

0

精彩评论

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