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'? –