Should I use a static or instance class in this specific case?

166 views Asked by At

I have read the posts regarding when to use static classes and when it is recommended to use instance classes. However, I have the impression my example below somewhat falls in between:

  • No class instances are needed, stored state is shared among members within the AppDomain.
  • State should be accessible from different class instances within the AppDomain.
  • No abstractions or overrides are ever needed.

So, my question is: Should I go ahead and use it as static or is it better to use a singleton concept?

public static class SubscriptionManager
{
    private static Dictionary<string, string> Repository { get; set; }

    static SubscriptionManager()
    {
        Repository = new Dictionary<string, string>();
    }

    public static void Subscribe(string key, string value)
    {
        if (Repository.ContainsKey(key))
            Repository[key] = value;
        else
            Repository.Add(key, value);
    }

    public static void Unsubscribe(string key, string value)
    {
        if (Repository.ContainsKey(key))
            Repository.Remove(key);
    }

    public static string GetSubscription(string key)
    {
        if (Repository.ContainsKey(key))
            return Repository[key];
        else
            return "";
    }
}
2

There are 2 answers

3
Murtaza Munshi On

Remember large static classes can take up a lot of memory so avoid them when not necessary. in this case i would suggest you to go with static classes. It is better this way.

1
M.Babcock On

Your example provides an explicit implementation of a Repository-like pattern which in the end may prove more valuable if it was extensible. If you implement this as a static class you're making the decision now that this should not be possible.

An example of another possibly valuable implementation might be to use the .NET 4 ConcurrencyDictionary<TKey, TValue> so the code can be used in higher volume, concurrent scenarios since the Dictionary class isn't thread safe.

What you're suggesting is very YAGNI, which is good for iterations of large project with some sort of plan in place, but unless you know what the future holds why limit the potential of code already written?

I'd probably generate an interface from your class to represent its bare bones (to separate the implementation from the contract), and utilize an IoC container to make the user of your class decide what implementation to use for their scenario.

Of course this only matters if your project is fairly small or otherwise care about sharing code between projects. Good luck!