Search code examples
javaoopdependency-injectioninversion-of-controldependency-management

Dependency Injection leads to main method being filled with new keywords


I have done proper dependency injection with constructors, but that makes my main method look like this:

MyModel myModel = MyModelFileReader.getModel(Config.getDefaultFile());
MyApp myApp = new MyApp(myModel, new View(new SubView(myModel), new SubView(myModel, new CustomChart(Config.getChartOptionOne(), Config.getChartOptionTwo)));
myApp.start();

All the constructing gets piled here, and it looks bad. What the proper way to do this?


Solution

  • To expand on the comment from @Nkosi, new has to called somewhere. Objects are instantiated by invoking their constructors, and dependency injection doesn't change that.

    If you apply a DI framework, that framework will take on the responsibility of instantiating objects, so you won't necessarily see the new keywords; but they are just hidden rather than eliminated.

    If you apply your own DI, then you implement a composition root yourself (which will be filled with new keywords). Your main method is exactly the right place to implement a composition root.

    Note the advantage of the composition root pattern is that it consolidates object instantiation (and thereby new keywords) in a single location. If you think of creating objects as a "single responsibility" then consolidating that work into main makes your codebase more cohesive.

    No pattern will eliminate the need to new up objects. By injecting dependencies through constructors, you're doing DI the right way.