I am programming in Windows Forms and MySQL. If I declare this in the program, I
ID: 643016 • Letter: I
Question
I am programming in Windows Forms and MySQL.
If I declare this in the program, I can use the connection and command objects in the whole .cs page:
MySqlConnection connection = null;
MySqlCommand command = null;
MySqlDataReader Reader;
But if I write the code below, connection and command objects are declared twice:
private void cmbo_class_SelectedValueChanged(object sender, EventArgs e)
{
string clas = cmbo_class.SelectedItem.ToString();
try
{
MySqlConnection connection = new MySqlConnection(hp.myConnStr);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select id,code from reg_class_master where name ='" + clas + "' and Delete_Status=0";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
class_id = Convert.ToInt32(Reader[0].ToString());
class_code = Reader[1].ToString();
}
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error in ","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
cmbo_division.Items.Clear();
try
{
MySqlConnection connection = new MySqlConnection(hp.myConnStr);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select name from reg_division_master where class_id = " + class_id + " and Delete_Status=0 order by display_index";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
cmbo_division.Items.Add(Reader[0].ToString());
}
connection.Close();
}
catch
{
}
I think one object declaration is the best way. Do more object declarations affect the program?
Explanation / Answer
Here are some rules that are almost always correct:
You should never reuse a variable for two different purposes.
The case when you need to, is a very specific one, and when you see it, you will know it (the flyweight pattern).
You should keep your methods very short.
The code you've shown can be logically contained in 3-5 methods at least.
You should not have duplicate code. (DRY = Don't Repeat Yourself)
Any similarly looking lines of code are most likely same functionality repeated in several places. Extract this in a single method.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.