0

我正在寻找一些程序设计指导。

我有一个处理数据库中数据的类库。我有一个 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。

我想我只是在寻找一些关于如何处理这种情况和验证/错误处理的指导。谢谢你的帮助。

4

2 回答 2

1

我想知道的第一件事是,当普通的控制流可能就足够了时,您是否需要抛出异常:

if (IsReadyForInput())
{
    //..open a DB connection and save out the data
    //..get the ID of the saved record
}
else 
{
    //..do whatever you need in case of invalid input
}

这个建议的明显问题是我们在您的类库中某处的方法中,并且一些期望的效果(向用户显示警告等)发生在 WinForms 层中。然而,这表明了一个更好的解决方案;即,在 WinForms 代码中进行验证:

if (IsReadyForInput())
{
    int result = theTool.SaveData();
    //...and whatever else should happen.
}
else
{
    //..do whatever you need in case of invalid input
}

与抛出异常或使用特殊返回值来表示失败相比,上述方法更简单,并且使程序的各个部分相互依赖更少(因为MyTool不需要关心用户输入的验证)。

于 2013-11-01T03:07:26.297 回答
0

看看 FluentValidation ( http://fluentvalidation.codeplex.com/ )。我想这就是你要找的。

使用它,您可以定义验证规则并调用其验证方法。它将返回潜在验证错误的完整列表,而不会在您的代码中引发异常。

于 2013-11-01T02:49:07.647 回答