Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I agree with Jason that this is more of a crosscutting concern.</p> <p>A function should really do only one function, as this makes the code more legible, and it becomes easier to test. For example, if my unit test is failing as the log file is full, that will be confusing, as I don't test the logging within my method.</p> <p>AOP is the best choice here, and for .NET PostSharp may be the best option.</p> <p>If AOP isn't a good option then you may want to use DI, and you can inject a version of the class that has logging, to test the flow, but if you are going to do this then you should ensure that the injected class just does the logging, then call the same function that doesn't have the logging, so you are putting a wrapper around your class.</p> <pre><code>public class ReallyIntenseCalculation : ICalculation { public int calculate(int number) { return DoTheDirtyWork(number); } private int DoTheDirtyWork(int number) { // crazy math happens here } } public class CalculationLoggingDecorator : ICalculation { ICalculation calculation; ILogger log; public CalculationLogging() { this.calculation = new ReallyIntenseCalculation() ; this.log = SomeLogger(...); log.Debug("Initialized 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); } } </code></pre> <p>This is similar to your decorator, but when you swap out the logging version for the non-logging version you have dropped all the excess code, and by testing the logging version you are ensuring that <code>ReallyIntenseCalculation</code> is being used and the methods are only defined one time.</p> <p>This is more work, and AOP is preferable, but DI may be an alternative.</p> <p><strong>UPDATE:</strong> Based on comment.</p> <p>If you have multiple classes extending this interface then you may have an explosion of classes, but design for that. </p> <p>AOP would be the best approach, but the concept is a hard sell to some companies, than DI. </p> <p>You may end up with two classes for each implementation, but your logging info is still removed from these other classes, have each class be injected in through DI, so you can have two app.config files, one with all the logging classes set up and one for production, to simplify your life. The second class just has the logging and set up info though, so it isn't too much extra work, I believe, but you have lost the fine granularity of logging.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload