简体   繁体   中英

Static methods inside class instance - good, bad or depends?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM