I'm making a console application that returns a lot of information directly to the console. I do this with a custom logger. Actually my logger implementation is just a frontend to print (with some extras).

The application is quite complex and I made it in DDD style, but one thing doesn't work for me - almost every business class that does something, I pass an instance of Logger through DI. First of all, this is very cumbersome, and secondly it obscures the code. Business classes have a Logger dependency that might as well be turned off, because if the action executes correctly, it doesn't return anything anyway.

The question is - do you pass the logger instance to your business classes explicitly via DI or do you have a global logger object that you use directly in the code? Or any other way? Maybe you have some rule of thumb for when DI and when global?


1 Answer 1


The safe default is to never use globals.

Sometimes, after finishing something it turns out that a global (aka singleton) would have sufficed, of course. And yes, passing dependencies seems like a chore. But the costs of always using DI are small, in comparison to the benefits.

  • Which are the benefits? And what makes you think a singleton is a global?
    – gnasher729
    Commented Sep 14, 2023 at 23:39
  • @gnasher729 A "singleton" is global by definition* - it's an instance reachable without a reference (this is what OP explicitly wants - avoid passing references). Passing references everywhere is (as OP notes) a chore, which is why all* Java applications use a DI framework (Spring, EJB, Guice, Dagger... earlier - Avalon, PicoContainer and such). The benefit of always using DI is 1) you never need micro-decisions 2) you get configuration for free 3) you can do any regression test, not just the ones forseen 4) you can easily reuse parts of your library. And the only cost is initial setup.
    – fdreger
    Commented Sep 15, 2023 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.