views:

43

answers:

3

I'm trying to get my head around the usage of the factory pattern, when I wish to disable features within an application.

Lets say for example I have a factory called LoggerFactory, which creates a logger instance.

If in the configuration logging is disabled in my application:

Should the logger factory pass back an instance of the logger that is a dummy, that doesn't do anything? So any code using the logger does not need to change.

Or, is it the responsibility of the code using the logger, not to use the logger if it is disabled in the configuration?

Or, is it the responsibility of the logger itself not to do anything, if it is disabled?

Thanks for the help.

+2  A: 

If you have many different logger-classes (e.g. log to file and log to network) then I think returning a dummy logger when logging is disabled is the simplest and most flexible solution. It will require no change to the code that uses the logger, and it will require no changes to the other loggers.

The idea of making the user of the logger responsible is bad, as that would spread the feature of disabling the logging through the entire code, thus polluting application logic.

Space_C0wb0y
+1  A: 

The code using the logger should not be involved in the enabled/disabled conditionality.

As to whether to use a Dummy disabled logger or just a stadanrd logger that knows it's disabled that's less obvious. Pragmatically I suspect that we'll tend to find that partial enablement is the most common scenario - some destinations or message classes will tend to be emitted when most are disabled. So I'd probably see this as the natural job of the logger to understand what it's configured to do.

I would go with the dummy only if this makes logger implementation very much easier and it's a common usage scenario.

djna
+2  A: 

IMHO, that's not a question about the principles of the factory pattern. It's more a question about the design of your coding style etc. But, just to provide an answer regarding your conrete question: It would be easier and more intuitive and more flexible (1) to return an object as an instance of an "empty" logger class or (2) to check the logging-disabled-flag within the regular logger class.

Flinsch
@Flinsch - good point on the principles, I've changed it to usage.
Alex Key
+1 for the emtpy logger
Andreas Hoffmann