我正在寻找一些程序设计指导。
我有一个处理数据库中数据的类库。我有一个 winforms 应用程序,它是用户输入和管理数据的表示层。例如,用户输入一些数据并尝试保存它。在 winforms 应用程序中,我执行以下操作:
MyTool theTool = new MyTool();
MyTool.FirstName = this.Textbox1.Text;
MyTool.LastName = this.Textbox2.Text;
//etc...
int result = MyTool.SaveData(); //result is the ID of the inserted record.
MyTool 是我的类库中的一种类型。在这种类型中,我将拥有:
public int SaveData()
{
if (IsReadyForInput())
{
//..open a DB connection and save out the data
//..get the ID of the saved record
}
else
{
throw new ArgumentException("One or more arguments prevented saving the data");
}
return theID
}
private bool IsReadyForInput()
{
if (this.FirstName.Length == 0)
{ return false; }
if (this.LastName.Length == 0)
{return false;}
return true;
}
现在,我感兴趣的是关于异常处理应该如何工作的最佳设计。例如,上面的方法根本不是特定的,所以用户不知道出了什么问题。所以我可以重写它来做类似的事情:
public void SaveData()
{
string errMess = IsReadyForInput();
if (errMess.Length == 0)
{
//..open a DB connection and save out the data
//..get the ID of the saved record
}
else {
throw new ArgumentException(errMess);
}
return theID
}
private string IsReadyForInput()
{
if (this.FirstName.Length == 0)
{ return "Specify a first name"; }
if (this.LastName.Length == 0)
{return "Specify a last name";}
return true;
}
但是,比较字符串长度以查找错误消息似乎并不是一种非常优雅(或快速)的方法。我曾尝试写类似的东西:
public void SaveData()
{
ValidateInput();
//..open a DB connection and save out the data
return theID
}
private void ValidateInput()
{
if (this.FirstName.Length == 0)
{ throw new ArgumentException("Specify a first name"; }
if (this.LastName.Length == 0)
{throw new ArgumentException("Specify a first name"; }
}
这样做的问题是,当前端调用“SaveData”时,ValidateInput 实际上会抛出异常,所以当异常到达顶部时,对我来说,它似乎不太清楚(特别是如果有多种调用“ValidateInput”的方法()" 来自 MyTool)。
此外,我不确定在前端处理异常的最佳方法是什么,因为如果抛出错误,则永远不会返回 ID。
我想我只是在寻找一些关于如何处理这种情况和验证/错误处理的指导。谢谢你的帮助。