devoured elysium
devoured elysium

Reputation: 105077

Preferable to embeb dependencies on interfaces or let that job to the concrete classes?

Here is a question that I have to face a lot when doing the design of my little apps. Is there a reason I should prefer

alt text

over

alt text

?

If yes, why? If not, are there any specific circunstances where there is a clear advantage in one approach over the other?

I tend to use the first approach, although I am not too sure why. I guess maybe it is because there may be some concrete implementation of IBonus that might not need a dependency at all, while the second approach is tieing me to something. A stub/mock class, for example.

Thanks!

Upvotes: 0

Views: 61

Answers (1)

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95509

It sounds like you understand the subject quite well. I agree with your argument that there might be an implementation which does not have the dependency and so it's best not to be tied down. I typically prefer the first approach, like you, for that very same reason and typically encourage that choice.

In general, I would say that if the dependency is an implementation detail, then it should be passed to the constructor of the concrete implementation. If the parameter is intrinsic to the very definition / nature of the computation, then it is better to pass in the parameter. Another situation where it is a good idea to pass the parameter in the interface is where mutation is concerned; for reentrance, it is better to pass a parameter that you modify over modifying the state of the implementation, so if any side-effects are expected, then I would encourage passing the object to be mutated. That aside, I agree with your view.

Upvotes: 3

Related Questions