0

If I am writing an API that takes an int parsed from a string, is it a good idea to seperate the parse method from the method that would do something with the "out" value?

My reason for thinking yes is that the code will be more clear. E.g. if I get an exception related to the parse, I can say in the stack "ah yes, that would be the top method called Parse() obviously!" before even looking at the codebase. I believe null is the wrong choice as it could introduce bugs by other developers who do not understand the technical decisions made (though I document this religously).

However, in a method that is 5 levels deep in the stack, how could I "Relay" an error string message?

Thanks

4

3 回答 3

0

你的问题有点不清楚。您是说您的方法采用一个字符串,该字符串应该可以解析为整数,然后对这种解析的数字结果进行处理?

如果您的方法不太可能收到大量无效字符串,并且如果您的例程在收到无效字符串时没有任何用处,那么您的方法最好在无效字符串出现时抛出异常传入。如果您的方法进行了足够复杂的解析,调用者无法很好地验证字符串而不做您的例程解析它的工作量,并且您的例程将被期望批量处理所有好的字符串包含好字符串和坏字符串的混合,一个常见的模式是公开一个bool TryParse(string st, ref int result). 就个人而言,我不喜欢这种模式,因为它没有提供任何机制来指示解析失败的原因。我会推荐一种不同的模式——类似于以下模式之一:

int TryParse(string st, out ParseStatus status);
int TryParse(string st, Action<ParseStatus> failureAction);
委托 void ActionRV<RefT,ValT>(ref RefT refparam, ValT valparam);
int TryParse<RefPT>(string st, ActionRV<RefT, ParseStatus> FailureAction,
                        参考参考参考参数);

在所有这三种调用模式中,如果ParseStatus是可继承类型,则可以TryParse提供精确描述故障的实例ParseStatus或派生类型。在第二种和第三种模式的情况下,委托可以自己抛出一个异常,存储在ParseStatus一个应该返回给调用函数的值中,或者可能做一些类似于 munge 原始参数字符串(如果它存储在 中ParseStatus)并设置一个请求“重试”的标志。我个人喜欢第三种形式,因为我认为ref在任何一种都可以工作的情况下,参数应该优于闭包。请注意,第二种形式可以按照第三种形式有效地实现:

静态 ExecAction<T>(T 参数,参考 Action<T> proc)
{
  过程(参数);
}
int TryParse(string st, Action<ParseStatus> failureAction)
{
  TryParse(st, ExecAction, ref failureAction);
}

请注意,传递failureActionref 参数意味着可以为包装函数使用静态委托,而不必使用闭包。

于 2012-06-13T15:25:31.457 回答
0

你应该让它抛出一个ArgumentException

于 2012-06-11T20:56:20.700 回答
0

为了传递错误字符串消息,创建一个异常并使用“throw”关键字。

至于分离 parse 方法,这是你要求的吗?

int myInt;
if(!Int32.TryParse(inputString, out int myInt))
    throw new System.ArgumentException("Invalid Argument", "inputString");

methodThatUsesInt(myInt);
于 2012-06-11T21:02:34.800 回答