I am trying to better understand the Dependency Injection pattern, and I came to the question whether a logger should be injected or not.
The language I am using is Python, but the concept is agnostic. What I do have now is just an import of a singleton logger module into the scope, and call it whenever necessary. As for example:
import logger
class Television(object):
def __init__(self, colour, inches):
self._colour = colour
self._inches = inches
def turn_on(self):
# do something
logger.message('TV has been turned on')
If I was using dependency injection, I would do something like this:
import logger
class Television(object):
def __init__(self, colour, inches, logger):
self._colour = colour
self._inches = inches
self._logger = logger
def turn_on(self):
# do something
self._logger.message('TV has been turned on')
Which makes the code more testeable (although python is so dynamic that while testing you could just mock on-the-fly the logger in the module).
The drawback is that I have to take care of the injection by using alternative constructors, some injection framework or service locator. I am not quite sure if the effort does pay off or not.
I've seen other similar questions, but I couldn't really understand them, or the answers did not satisfy me:
Is it a good practice to have logger as a singleton?