以下是C#,尽管代码模式可能与任何OO语言相关。
我有两个方法,MethodWithTry 和 MethodWithSomeReturnValue,我认为它们在功能上是等效的。我想知道其中之一是否是"正确"的方式。是否有关于一个(例如并发(的东西使其中一个成为糟糕的选择。
public void MethodWithTry()
{
int returnValue;
string someInput;
if (TryGetValueThisWay(someInput, returnValue))
{
//do something this way
}
else
{
if (TryGetValueThatWay(someInput, returnValue))
{
//do something that way
}
else
{
//do something a default way
}
}
}
public void MethodWithSomeReturnValue()
{
int? returnValue;
string someInput;
returnValue = GetValueThisWay(someInput);
if (returnValue != null)
{
//do something this way
}
else
{
returnValue = GetValueThatWay(someInput);
if (returnValue != null)
{
//do something that way
}
else
{
//do something a default way
}
}
}
被调用方法的签名是
public int? GetValueThisWay(string input)
public int? GetValueThatWay(string input)
private bool TryGetValueThisWay(string input, out int value)
private bool TryGetValueThatWay(string input, out int value)
编辑 -- 附加信息
被调用的有问题的方法正在集合中进行查找。所以不同的名字可能是
public int? GetValueFromCollectionA()
public int? GetValueFromCollectionB()
恕我直言,TrySomeMethodName - 使代码更具可读性。但是,使用 OUT 变量(尤其是当返回值为整数时(意味着它始终是可变的,并且至少分配给两次(默认值设置为 0(。
如果你对值类型(如int
(进行操作,并且你的方法的结果可以null
,你应该选择Try
版本。这是因为值类型不能很好地与null
混合。例如,由于?
引入的拳击,int?
比int
慢得多。所有 .NET TryParse
方法都使用值类型,并且它们遵循此模式。我认为遵守这种方法是件好事。
当您开始对引用类型进行操作时,使用方法结果并在需要时返回null
变得更加自然。
根据今天编写此方法的返回类型 - 假设操作可能会失败,并且这是整个工作流的一部分 - 我将返回一个可为空的结构,或一个null
引用值而不是Tryxxx
方法 - 在我看来,必须使用out
值相当麻烦。
public int? MethodWithSomeReturnValue()
{
//return null in failure case
}
int? result = MethodWithSomeReturnValue();
if(result != null)
{
//...
}
嗯,这取决于。也许这将是你从每个有意愿回答你的人那里得到的答案。有时你知道或者你可以假设一个值总是来自某种类型,你可以使用 GetValue 或 ConvertToInt32(例如(,例如从具有定义类型的数据库中获取值。但其他时候你不能信任输入,你不确定它是哪种类型,比如用户输入......在这种情况下,您可以建议使用 TryGetValue 或 TryParse(例如(。所以最终这取决于你。