Test-driven Development practice-Introductory article we talked about some basic test-driven development processes:
1. Write unit tests to make him light a red light
2. Write code to turn the test into a green light
3. Refactoring code
Next we need to start refactoring, and you might ask why you need to refactor and when to refactor.
The reason why refactoring is necessary is to make the code structure clear, to remove some duplicate code, such as we execute the SQL statement operation, we originally wrote
Code
1private connStr="server=.;database=TestDB;uid=sa;pwd=123"
2public int Add(string loginName)
3{
4 int count = 0;
5 using (SqlConnection conn = new SqlConnection(connStr))
6 {
7 conn.Open();
8 SqlCommand cmd = new SqlCommand("insert(loginName) value('" + loginName + "')", conn);
9 count = cmd.ExecuteNonQuery();
10 cmd.Dispose();
11 conn.Close();
12 }
13 return count;
14}
15
16public int Delete(string loginName)
17{
18 int count = 0;
19 using (SqlConnection conn = new SqlConnection(connStr))
20 {
21 conn.Open();
22 SqlCommand cmd = new SqlCommand("delete from LoginUsers where loginName='" + loginName + "'", conn);
23 count = cmd.ExecuteNonQuery();
24 cmd.Dispose();
25 conn.Close();
26 }
27 return count;
28}
We found that everything else is the same except for the SQL statements, so we can refactor
Code
1private int ExecuteSql(string sql)
2{
3 int count = 0;
4 using (SqlConnection conn = new SqlConnection(connStr))
5 {
6 conn.Open();
7 SqlCommand cmd = new SqlCommand(sql, conn);
8 count = cmd.ExecuteNonQuery();
9 cmd.Dispose();
10 conn.Close();
11 }
12 return count;
13}
14public int Add(string loginName)
15{
16 return ExecuteSql("insert(loginName) value('" + loginName + "')");
17}
18public int Delete(string loginName)
19{
20 return ExecuteSql("delete from LoginUsers where loginName='" + loginName + "'");
21}