Is it bad practice to put most variables at class level in a Form? Would these be considered global variables?
public partial class Form1 : Form
{
private string mode;
private int x, y;
public Form1()
{
InitializeComponent();
}
}
I'm using the variables in multiple controls when I declare them at class level.
What i get from the question is that if you are using as a Individual form that is not dependent on any form then all this variables will be private variables to the class. And if the form is called from somewhere else. Then also it will be private variables. If you really want to make a clear design then you can Create public properties over private variables that you want to expose to other class.
In that way you can put a limit access to the other class to the private variables by creating read only properties so that other classes cannot modify but can access it.
Those would be considered class-level globals (to distinguish from application globals.) The more important distinction in this case is that they are private
to the class.
Class-level globals have their uses, so I definitely wouldn't call it a bad practice. A very good use for private class globals is when you plan to expose them through property accessors. For example:
public readonly
properties whose values are controlled by logic internal to your class.
public
properties with both set
and get
accessors (enabling custom validation logic in setter.)
However, I would say it's a good practice to make things local unless otherwise necessary. The reason is that you have less mutable state belonging to a class instance, so there is less potential for bugs like this:
private int EvilMethod1() {
x = (int) Math.Pow((double) y, 2);
return x;
}
private int EvilMethod2() {
y = (x + y) * 2;
return y;
}
// Assignments depend on the current values of x and y,
// as well as yielding unexpected side effects.
private void PureEvil()
{
// Return value depends on current y; has side effect on x while assigning y.
y = EvilMethod1();
// Return value depends on current x and y; has side effect on y while assigning x.
x = EvilMethod2();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With