This is more of a theoretical question. Should logging reside within a class who's primary purpose is not logging?
Here is a simple interface for anything that will preform a calculation on a number.
public interface ICalculation {
public int calculate(int number);
}
Here is an implementation of the ICalculation interface that performs a calculation and does some logging. I believe this is a very pragmatic approach. Aside from the constructor accepting something that we wouldn't normally expect to see in a calculation's domain, the inline logging is arguably non intrusive.
public class ReallyIntenseCalculation : ICalculation {
private readonly ILogger log;
public ReallyIntenseCalculation() : this(new DefaultLogger()) {
}
public ReallyIntenseCalculation(ILogger log) {
this.log = log;
log.Debug("Instantiated a ReallyIntenseCalculation.");
}
public int calculate(int number) {
log.Debug("Some debug logging.")
var answer = DoTheDirtyWork(number);
log.Info(number + " resulted in " + answer);
return answer;
}
private int DoTheDirtyWork(int number) {
// crazy math happens here
log.Debug("A little bit of granular logging sprinkled in here.");
}
}
After removing all the logging code from ReallyIntenseCalculation, the code now has what appears to be a clear single responsibility.
public class ReallyIntenseCalculation : ICalculation {
public int calculate(int number) {
return DoTheDirtyWork(number);
}
private int DoTheDirtyWork(int number) {
// crazy math happens here
}
}
Ok, so we have removed ReallyIntenseCalculation's ability to log its internals. How can we find a way to externalize that functionality. Enter the decorator pattern.
By creating a class that decorates an ICalculation we can add logging back into the mix, but doing so will compromise some of the more granular logging that was taking place within ReallyIntenseCalculation's private methods.
public class CalculationLoggingDecorator : ICalculation {
private readonly ICalculation calculation;
private readonly ILogger log;
public CalculationLoggingDecorator(ICalculation calculation, ILogger log) {
this.calculation = calculation;
this.log = log;
log.Debug("Instantiated a CalculationLoggingDecorator using " + calculation.ToString());
}
public int calculate(int number) {
log.Debug("Some debug logging.")
var answer = calculation.calculate(number);
log.Info(number + " resulted in " + answer);
}
}
What are some of the other possible pros and cons of having a logging decorator?