Question

Say I make a static class like following with an extension method:

public static class MyStaticExtensionClass
{
    private static readonly Dictionary<int, SomeClass> AlgoMgmtDict
        = new Dictionary<int, SomeClass>();

    public static OutputClass ToOutput(this InputClass input)
    {
        // clears up the dict
        // does some kind of transform over the input class
        // return an OutputClass object
    }    
}

In a multi user system, will the state management dictionary fail to provide correct values for the transform algorithm? Will a regular class be a better design or shoving the Dictionary inside the method a better design?

Was it helpful?

Solution

There are only three scenarios available for your dictionary: either it must be shared, or it must not be shared, or you don't know or care.

If it must be shared, you'll have to implement proper locking. But since the first thing you're doing in ToOutput() is to clear the dictionary, it doesn't look like sharing it will bring you many advantages.

So, we're down to the two remaining scenarios (must not be shared, or don't know or care), and in both cases it would be better to isolate the dictionary in a local variable inside ToOutput():

public static OutputClass ToOutput(this InputClass input)
{
    Dictionary<int, SomeClass> algoMgmtDict = new Dictionary<int, SomeClass>();
    // Dictionary starts up empty, no need to clear anything.

    // Do some kind of transform over the `input` object.
    // Return an OutputClass instance.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top