Dependency Injection vs Encapsulation?

Let me start by saying that I LOVE the concept of dependency injection (DI) and feel that it should be utilized as much as possible. However, it seems to be somewhat contradictory to a concept that was drilled into me starting with my first programming classes: encapsulation.

Let me illustrate the conflict with an example. Proper DI techniques say that you should create your classes along these lines:

Where this seems to go against the concepts of encapsulation, is the fact that instances of Bar and Baz now have to exist outside of the Foo class. If interaction with those classes is not needed outside of the Foo class, wouldn’t it be better to hide it’s existence all together?

The example above might seem a bit trivial, but what if the creation of a Bar instance was very complex, but still requires nothing outside of the Foo class in order to create it?

Am I missing something? Even if they are conflicting paradigms, I think DI is the better option, but are they really conflicting?

2 Responses to Dependency Injection vs Encapsulation?

  1. Pingback: Chris Hartjes

    • Pingback: chase

Leave a Reply