在公共(public) API 中返回函数调用的结果有几种不同的常见模式。哪个是最好的方法并不明显。是否就最佳实践达成普遍共识,或者至少有令人信服的理由说明一种模式优于其他模式?
更新 对于公共(public) API,我指的是公开给依赖程序集的公共(public)成员。我不是专门指作为网络服务公开的 API。我们可以假设客户正在使用 .NET。
我在下面编写了一个示例类来说明返回值的不同模式,并且我对它们进行了注释以表达我对每个模式的关注。
这是一个有点长的问题,但我确信我不是唯一考虑过这个问题的人,希望其他人也会对这个问题感兴趣。
public class PublicApi<T> // I am using the class constraint on T, because
where T: class // I already understand that using out parameters
{ // on ValueTypes is discouraged (http://msdn.microsoft.com/en-us/library/ms182131.aspx)
private readonly Func<object, bool> _validate;
private readonly Func<object, T> _getMethod;
public PublicApi(Func<object,bool> validate, Func<object,T> getMethod)
{
if(validate== null)
{
throw new ArgumentNullException("validate");
}
if(getMethod== null)
{
throw new ArgumentNullException("getMethod");
}
_validate = validate;
_getMethod = getMethod;
}
// This is the most intuitive signature, but it is unclear
// if the function worked as intended, so the caller has to
// validate that the function worked, which can complicates
// the client's code, and possibly cause code repetition if
// the validation occurs from within the API's method call.
// It also may be unclear to the client whether or not this
// method will cause exceptions.
public T Get(object argument)
{
if(_validate(argument))
{
return _getMethod(argument);
}
throw new InvalidOperationException("Invalid argument.");
}
// This fixes some of the problems in the previous method, but
// introduces an out parameter, which can be controversial.
// It also seems to imply that the method will not every throw
// an exception, and I'm not certain in what conditions that
// implication is a good idea.
public bool TryGet(object argument, out T entity)
{
if(_validate(argument))
{
entity = _getMethod(argument);
return true;
}
entity = null;
return false;
}
// This is like the last one, but introduces a second out parameter to make
// any potential exceptions explicit.
public bool TryGet(object argument, out T entity, out Exception exception)
{
try
{
if (_validate(argument))
{
entity = _getMethod(argument);
exception = null;
return true;
}
entity = null;
exception = null; // It doesn't seem appropriate to throw an exception here
return false;
}
catch(Exception ex)
{
entity = null;
exception = ex;
return false;
}
}
// The idea here is the same as the "bool TryGet(object argument, out T entity)"
// method, but because of the Tuple class does not rely on an out parameter.
public Tuple<T,bool> GetTuple(object argument)
{
//equivalent to:
T entity;
bool success = this.TryGet(argument, out entity);
return Tuple.Create(entity, success);
}
// The same as the last but with an explicit exception
public Tuple<T,bool,Exception> GetTupleWithException(object argument)
{
//equivalent to:
T entity;
Exception exception;
bool success = this.TryGet(argument, out entity, out exception);
return Tuple.Create(entity, success, exception);
}
// A pattern I end up using is to have a generic result class
// My concern is that this may be "over-engineering" a simple
// method call. I put the interface and sample implementation below
public IResult<T> GetResult(object argument)
{
//equivalent to:
var tuple = this.GetTupleWithException(argument);
return new ApiResult<T>(tuple.Item1, tuple.Item2, tuple.Item3);
}
}
// the result interface
public interface IResult<T>
{
bool Success { get; }
T ReturnValue { get; }
Exception Exception { get; }
}
// a sample result implementation
public class ApiResult<T> : IResult<T>
{
private readonly bool _success;
private readonly T _returnValue;
private readonly Exception _exception;
public ApiResult(T returnValue, bool success, Exception exception)
{
_returnValue = returnValue;
_success = success;
_exception = exception;
}
public bool Success
{
get { return _success; }
}
public T ReturnValue
{
get { return _returnValue; }
}
public Exception Exception
{
get { return _exception; }
}
}
最佳答案
Get - 如果验证失败是意外的,或者调用者可以在调用方法之前自行验证参数,则使用此方法。
TryGet - 如果预期验证失败,请使用它。由于 TryXXX 模式在 .NET Framework 中的常见用途(例如 Int32.TryParse 或 Dictonary<TKey, TValue>.TryGetValue ),因此可以认为它很熟悉。
TryGet with out Exception - 异常可能表示作为委托(delegate)传递给类的代码中的错误,因为如果参数无效则
_validate
将返回 false 而不是抛出异常,并且_getMethod
将不会被调用。GetTuple、GetTupleWithException - 以前从未见过这些。我不会推荐它们,因为 Tuple 不是 self 解释的,因此不是公共(public)接口(interface)的好选择。
GetResult - 如果
_validate
需要返回比简单 bool 值更多的信息,请使用它。我不会用它来包装异常(参见:TryGet with out Exception)。
关于c# - 哪种结果模式最适合公共(public) API,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6781463/