在这个问题中,我将询问基本的实践。今天我面临的情况是,我需要用这段代码更新数据库表值。更好的清洁功能代码或大块代码
public void updateUsrProfileName(string usrId, string name)
{
query = "update [db_user].[dbo].[usr_profiles] set [Name][email protected] where [usrid][email protected] ";
try
{
com = new SqlCommand(query,con);
com.Parameters.AddWithValue("@name",name);
com.Parameters.AddWithValue("@usrid",usrId);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (Exception e)
{
con.Close();
throw e;
}
}
我需要重复上面的表中的每一列函数,所以我想出了一个共同的功能,以减少代码
public void Commonfunction(SqlCommand com, string var)
{
try
{
com.Parameters.AddWithValue("@usrid", var);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (Exception e)
{
con.Close();
throw e;
}
}
,并调用上面的函数类似这样的
public void updateUsrProfileName(string usrId, string name)
{
query = "update [db_user].[dbo].[usr_profiles] set [Name][email protected] where [usrid][email protected] ";
try
{
com = new SqlCommand(query,con);
com.Parameters.AddWithValue("@name",name);
Commonfunction(SqlCommand com, string name);
}
catch (Exception e)
{
con.Close();
throw e;
}
}
优点: - 干净的代码没有冗余。 更少的代码长度,其在差
缺点非常少: - 由于没有函数调用提高性能下降,因为它需要匹配参数,映射函数调用等
在这种情况下非常较小的代码是多余的移动是否具有共同的功能,以及在哪些条件下我们应该考虑功能划分还是不划算。
更新整个记录。只写一个'updateUserProfile(UserProfile配置文件)'函数。 – sbenitezb
我认为这会浪费资源,好像只需要更新名称为什么我应该向上移动整行就会影响性能 –
您每秒更新一次用户配置文件多少次?不是一次,我猜想。 – sbenitezb