I have the main class:
class MainClass
{
public static void Main()
{
InputForm InputForm1 = new InputForm();
InputForm1.ShowDialog(); // show interface to prompt user
}
}
that simply calls a windows form. This has the following class:
public partial class InputForm : Form
{
public InputForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// do some calculation and then create a dictionary of items
for (int n = 1; n <= dict.Count; n++) // loop through items
{
LengthClass theLength = new LengthClass();
dict[n].calculatedLength = theLength.calcLength(arg1, arg2, dict[n].speed);
}
}
}
When the button is clicked, the program does some calculation on data that are read from a spreadsheet and save results into a dictionary. Each element is an animal and I have some properties that I store in the dictionary (e.g. under the key "Dog" I have an average weight of dogs, an average speed, etc.). Using the speed and two default arguments (arg1 and arg2) I have to call the method of the class LengthClass in order to get the estimated length that is covered by the specific animal in arg1 hours and arg2 minutes. The LengthClass is like this:
class LengthClass
{
public double calcLength(double arg1, double arg2, double speed)
{
// do some calculation
return x;
}
}
Now my doubt is how to better design the code. When looping through each key in the dictionary I instantiate each time a LengthClass and call its method. Is this the right things to do? I would like to keep the method to calculate the length separate from the code in the windows form so that it is easier to change it if necessary. But I think that instantiating the class everytime might slow down the code and that a better design could keep the code fast and easy to read. Any suggestion?
Thanks to answers below, it seems that declaring the method calcLength as static would solve the problem and avoid the need of a recurring instantiation of LengthClass. But if LengthClass has an additional method, say calcLength2(), that in order to perform the calculations need to call the methods of a new class, say helpClass, do I need to declare methods of helpClass as static in order to avoid instantiations of helpClass when calling its methods from my calcLength2() in LengthClass?