-3

I have a small project that has 6 service classes and a main class. Since they are service classes and does not store any state in it, I declared one static method in each one:

  • class Main calls A.foo1(param)
  • A calls (in static foo1 method) B.foo2(param2)
  • B calls (in static foo2 method) C.foo3(param3)
  • and so on...

Recently I've decided to apply dependency injection with constructor injection. First, I changed static methods to normal methods and I had to create a huge A object in main:

new A(new B(new C(new D(new E(...)))));

Is there a cleaner way to achieve this? It seems ugly to me and using Spring (Java's popular framework containing DIC) for only 6 classes seems unnecessary.

Andy
  • 10,238
  • 4
  • 25
  • 50
  • It's hard to answer this with such an abstract example. The solution may lie in thinking about what each of these classes is for, and what dependencies they actually need. – IMSoP Apr 12 '21 at 09:38
  • 1
    Personnaly i consider this as duplicate of https://softwareengineering.stackexchange.com/questions/190120/should-i-use-dependency-injection-or-static-factories?rq=1. Currently what you have done is only a 6 classes things, but lot of stuff start small and get bigs through the times. So I would rather prefer to profit that the project is small and have a lightweight but properly DI configuration. So if others people get your old code for something bigger, they already have a decent base. – Walfrat Apr 12 '21 at 11:00
  • See this overview from the author of Dependency Injection in .NET: https://blog.ploeh.dk/2012/11/06/WhentouseaDIContainer/ – Filip Milovanović Apr 14 '21 at 17:33

1 Answers1

0

Writing your custom implementation of dependency inversion is a great way to teach yourself the concepts. However, in a real world scenario, using a framework to take care of that for you will almost always be the better option. It's almost, because as always, there are situations in which you will need to rely on your own implementation. E.g. when programming something for an embedded system which cannot accommodate the entire framework, due to the system's HW restrictions.

There's really nothing wrong with using Spring even for small projects, it being as popular as it is. It's true that Spring is capable of a lot of stuff and it may seem like you're bringing too much into the project right from the start. If that's not your preference, you could grab a framework which deals solely with the IoC problem, e.g. Google's Guice. However be advised, Spring, although heavy, prepares the ground for your project to seamlessly grow into something bigger, without you needing to change the underlying technology, as Spring has a lot to offer even for enterprise level applications.

Andy
  • 10,238
  • 4
  • 25
  • 50