Search code examples
c#wpfstaticshared-data

Why using static classes to share global data is not a good practice?


I have heared that sharing data using static class properties is not a good practice. Although I haven't seen any one using this approach but I can't find out what are the drawbacks for such appraoch! To be more clear, Let's consider a WPF application composed of many UserControls that share data and parameters in a certain flow; using a static reference will make it easy to access/share these data, but no one seems to like this approach, Why?

I am expecting an anti-pattern related answer, I am just not sure what it is.


Solution

  • If it is only about parameters setup, don't see any problem with sharing them among different parts of application, instead of have multiple copies of the same data. It still stays on shoulders of SOLID principles, as the responsibility of that class is holding parameter/configuration options.

    If you have also data, it becomes little bit more complicated. There is no one single best answer to this. Having data in one place violates SOLID principle, and

    • will be harder to write Unit Test
    • find bugs
    • harder to manage inside multi-threaded environment.

    Note the word "harder", but not impossible.

    On positive side

    • in modern computer architectures computations are way cheap then moving data from one place to another. so if you have compute intensive application, create data once and access it from different places is usually a better choice then pass it all around.

    • if you have multihtreaded, compute intensive application and by design of your data can guarantee no raise conditions on it, data-wise, it still is a better choice then having multiple copies. Create, copy/move memory is expensive.

    Saying that. If you worry only about controls and UI stuff, I would suggest to

    • configuration parameters keep in one static class (considering that you need single configuration setup during single run)
    • data information move to every class, which is responsible for it.