Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

27
  • 9
    You've described not the equivalent, but the opposite of dependency injection. In your model, every object needs to know the concrete implementation of all its dependencies, but using DI that becomes the responsibility of the "main" component - to glue appropriate implementations together. Bear in mind that DI goes hand-in-hand with the other DI - dependency inversion, where you do not want high-level components to have hard dependencies on low-level components. Commented May 30, 2018 at 6:21
  • 2
    its neat when you have only one level of class inheritance and one level of dependencies. Surely it will turn into hell on earth as it expands? Commented May 30, 2018 at 11:04
  • 6
    if you use interfaces and move initializeDependencies() into the constructor its the same but neater. The next step, adding construction parameters means you can do away will all your TestClasses. Commented May 30, 2018 at 11:05
  • 8
    There is so much wrong with this. As others have said, your 'DI equivalent' example is not dependency injection at all, it is the antithesis, and demonstrates a complete lack of understanding of the concept and introduces other potential pitfalls as well: partially initialized objects are a code smell As Ewan suggests, Move the initialization to the constructor, and pass them via constructor parameters. Then you have DI... Commented May 30, 2018 at 23:14
  • 3
    Adding to @Mr.Mindor: there's a more general anti-pattern "sequential coupling" which doesn't just apply to initialisation. If methods of an object (or, more generally, calls of an API) must be run in a particular order, e.g. bar can only be called after foo, then that's a bad API. It's claiming to provide functionality (bar), but we can't actually use it (since foo might not have been called). If you want to stick with your initializeDependencies (anti?)pattern, you should at least make it private/protected and call it automatically from the constructor, so the API is sincere. Commented May 31, 2018 at 12:35