C# – Should I use static classes for methods that will do common tasks and would be called through out the application

asp.net-mvccobject-oriented-design

I have spent the last few hours reading up on the use of static classes and trying to figure out if I should be using them or not but still have not come to any sort of conclusion. It seems that the argument could go either way. In my application I have created what I call "helper classes" which contains methods that will do very common tasks for me and would be called through out my application (ASP.Net MVC Web App using C#) and the simple question is, should they really be static or not?

Here is an example of one of my helpers.

public static class ActiveDirectoryHelper
{
    public static PrincipalContext GetPrincipalContext(string ouName)
    {
        var fullOUName = string.Concat("OU=", ouName,",DC=");

        return new PrincipalContext(ContextType.Domain, "", fullOUName, ConfigurationManager.AppSettings["ServiceAccountUser"], ConfigurationManager.AppSettings["ServiceAccountPassword"]);
    }

    public static PrincipalSearcher GetAllUsersInOU(string ouName)
    {
        var principalContext = GetPrincipalContext(ouName);
        var userPrincipal = new UserPrincipal(principalContext);
        return new PrincipalSearcher(userPrincipal);
    }

    public static UserPrincipal GetUserPrincipal(string userName, string ouName)
    {
        var principalContext = GetPrincipalContext(ouName);
        return UserPrincipal.FindByIdentity(principalContext, userName);
    }
}

Best Answer

I think static classes are nice in many cases. I could just say "use them when it's useful" but that's not very helpful.

My rule of thumb is (as always): Am I hiding any dependencies? If you feel like a "helper class" is useful (although beware of low cohesion) then by all means, go ahead. Just make sure your methods don't access global state though. Pure static methods are lovely. Static methods that depend on some globals or that open DB connections or read from disk/some config file are ticking time bombs.

They make testing the application really hard (the only way of doing it will be manually running the whole system, or with brittle automatic full-system tests, you'll get no granularity). They also make it impossible to swap out implementations.

Just remember the dependency inversion principle and the open/closed principle! Make sure your classes are pluggable. Make sure they don't pull stuff out of thin air. If you do that, then go ahead and make as many static methods as you want!

Related Topic