Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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?

like image 734
John Ohara Avatar asked Nov 26 '15 13:11

John Ohara


1 Answers

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);
    }
}
like image 123
Andrei Avatar answered Oct 08 '22 00:10

Andrei