0
我想有一个函数验证对象。函数返回一个布尔结果,并在错误返回的情况下显示错误
如果出现错误结果,我想知道为什么我的对象无效。
这是一个样的算法:
public bool ValidObject(MyObjectClass obj)
{
if(obj==null)
{
throw Exception("obj cannot be null");
return false;
}
if(obj.A=='x'){
throw Exception("obj cannot be x");
return false;
}
....
....
// other validations
....
...
if(obj.Students.Count()==100)
{
throw Exception("some error message");
return false;
}
return true;
}
如果我打电话给我的功能:
if(ValidateObject(this.Obj))
{
InsertIntoDB(this.Obj);
}
else
{
//do something
}
我会,如果我的对象是无效的得到一个错误。但我不想要这个。
但也许在某些情况下,我想知道为什么我的对象是无效的。
我不想让功能相同,但其中一个引发异常。我不认为这是一个正确的方法。
所以,我首先想到的是让先前的功能私营和创建另一个公共职能:
public bool ValidObject2(MyObjectClass obj, bool withErrors=false)
{
try
{
return ValidObject(obj);
}
catch(Exception ex)
{
if(withErrors)
{
throw ex;
}
return false;
}
}
你觉得呢?你有其他想法吗?
为什么不直接在调用者中使用'try..catch'? –