我最近与一位朋友谈论返回值只取一个意思。在我以前的工作中,我们使用C++并且使用了typedef处理的wBOOL,所以0表示wFALSE,1表示wTRUE。建筑师说,我们也可以返回2,3,4 ......以获取更多信息,我认为这是一个可怕的想法。如果我们期望wTRUE = 1和wFALSE = 0且wBOOL = {wTRUE,wFALSE},则应避免返回任何其他内容......现在转到今天的C#。使用返回的错误消息,以确定是否存在错误
我最近审查了一段代码,那里有功能的集合,确定是否有错误,返回的字符串返回给用户:
private bool IsTestReady(out string errorMessage)
{
bool isReady = true;
errorMessage = string.Empty;
if(FailureCondition1)
{
isReady = false;
errorMessage = FailureMessage1;
}
else if(FailureCondition2)
{
isReady = false;
errorMessage = FailureMessage2;
}
//... other conditions
return isReady;
}
然后,要使用这些功能...
private enum Tests
{ TestA, TestB, TestC }
private void UpdateUI()
{
string error = string.Empty;
bool isTestReady;
switch(this.runningTest) // which test are we running (TestA, TestB, or TestC)
{
case Tests.TestA:
isTestReady = IsTestAReady(error);
break;
case Tests.TestB:
isTestReady = IsTestBReady(error);
break;
case Tests.TestC:
isTestReady = IsTestCReady(error);
break;
}
runTestButton.Enabled = isTestReady;
runTestLabel.Text = error;
}
我认为这些出分成两种方法:
private string GetTestAErrorMessage()
{
//same as IsTestReady, but only returns the error string, no boolean stuffs
}
private bool IsTestAReady
{
get{ return string.IsNullOrEmpty(GetTestAErrorMessage()); }
}
这是否违背了不具有返回值意味着不止一件事的原则?例如,在这种情况下,如果出现错误消息IsNullOrEmpty,那么就没有错误。我认为这不违反该委托人;我的合作确实如此。对我来说,这是没有什么不同:
class Person
{
public int Height {get;}
public bool IsTall() { return Height > 10; }
}
对这个问题的不同方法的任何想法或建议?我认为out参数是最差的解决方案。
顺便说一句,我没有添加关于Person类的最后一点,它与我不一样。在这种情况下,高度的存在并不意味着天生的;但是错误信息的存在确实意味着存在错误。 – MPavlak 2012-08-27 14:07:44