I have an old guard class - it constisted or static methods, typical of a utilty class.
However, recently I've started to use NLog - so my guards can now log as well as throw. The thing is with NLog that each calling class (where the guard resides) creates its own logger, so instead of a method like this:
public static void NotNull<T>(T obj, string param)
{
if (obj.Equals(null))
throw new ArgumentNullException(param);
}
I have a method with a signature like this:
public static void NotNull<T>(T obj, string param, Logger logger, LogLevel logLevel)
{
}
Now all my methods contain the two same parameters relating to the logger, so I've almost decided that dependency injection would be a better approach, passing the logger into the constructor, and obj into the method.
The question I have is based on my inexperience - my new class won't be static, but should I leave the methods inside as static?
It does not seem like you need to pass in logger at all. It is fine and not against the common practice to have a static logger field (look at this answer for details), so that it is shared across all instances of the class. Consider:
public static class Utils
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Utils));
public static void NotNull<T>(T obj, string param)
{
Log.Debug("Huston, we got a null.");
if (obj.Equals(null))
throw new ArgumentNullException(param);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With