1

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?

6
  • One option is to use the Decorator pattern for the loggers - you create a transparent wrapper that logs around relevant operations, then instead of your regular instances, you inject wrapped instances. Commented Aug 15, 2023 at 14:48
  • 1
    Does this answer your question? Should I use a global logging variable? Commented Aug 15, 2023 at 15:07
  • Does this answer your question? Should I use a global logging variable? Commented Aug 15, 2023 at 17:05
  • You might want to review: web.archive.org/web/20120826171609/http://… Commented Aug 15, 2023 at 22:42
  • Welcome. The question in its current state looks like a "poll-style question", which is likely to be closed. Express the question part differently. Commented Aug 17, 2023 at 9:30

1 Answer 1

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.

2
  • Which are the benefits? And what makes you think a singleton is a global? 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. Commented Sep 15, 2023 at 7:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.