我最近和一个朋友谈论返回值只具有单一含义。在我之前的工作中,我们使用 C++ 并定义了 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 参数是最糟糕的解决方案。