Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using static classes whenever i can good practice?

Let me be more precise. In my winforms project im creating classes to manage/create every part of the program. I did it to have more control over my code. E.g. I have a class that manages my DataGridView control. I named it gridManager and in it i set all properties, colors and so on and also i have methods to change those settings (e.g. changeBackgroundColor() etc). I also have this type of class for each Panel in splitContainer. In those classes i initialize every Control that is a child of panel i add them to that panel set all properties and so on.

I wrote it all to give you better view at the purpose of those classes.

Now my question is: is it good practice to make this classes static? With all controls and methods inside being static?

At first i had them non-static but when i wanted to call methods for (e.g.) changing color from options Form i had to either pass MainForm as a parameter or do it like this:

(Application.OpenForm[0] as MainForm).gridManager.changeColor();

Static version of it makes it a lot easier. But it makes me wonder if its a good thing to do. Uh a lot of explaining i hope my not perfect English wont make it even more difficult to understand. :)

like image 731
Brazol Avatar asked Dec 21 '22 12:12

Brazol


1 Answers

Global mutable state is usually a bad idea.

Static methods/classes are good for simple sideeffect free functions. Math and Enumerable are good examples.

You on the other hand want controls inside static fields. These are mutable state and thus should be avoided. For example if you tomorrow want to have two instances of your form, you need two instances of your manager class. But it's static and you now need to rewrite all the code using it.

like image 164
CodesInChaos Avatar answered Dec 24 '22 01:12

CodesInChaos