哪种结果模式最适合公共API,为什么?

sma*_*man 5 c# api-design tuples return-value out-parameters

在公共API中返回函数调用的结果有一些不同的常见模式.目前尚不清楚哪种方法最好.是否对最佳实践达成了普遍共识,或者至少是令人信服的理由为什么一种模式比其他模式更好?

更新通过公共API,我指的是暴露于依赖程序集的公共成员.我并不是指公开作为Web服务公开的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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

dtb*_*dtb 6

  • 获取 - 如果验证失败是意外的,或者调用者在调用方法之前自己验证参数是否可行,则使用此选项.

  • TryGet - 如果预期验证失败,请使用此选项.TryXXX模式可以被认为是熟悉的,因为它在.NET Framework中很常见(例如,Int32.TryParseDictonary <TKey,TValue> .TryGetValue).

  • TryGet with out Exception - 异常可能表示代码中传递给代表的代码中的错误,因为如果参数无效则_validate返回false而不是抛出异常而_getMethod不会被调用.

  • GetTuple,GetTupleWithException - 从未见过这些.我不推荐它们,因为元组不是自我解释的,因此不是公共接口的好选择.

  • GetResult - 如果_validate需要返回比简单bool更多的信息,请使用它.我不会用它来包装异常(参见:TryGet with out Exception).

  • 我还补充说,有一种标准的方法可以使用内联XML文档来记录抛出的异常.这些例外显示在Intellisense中,并且在使用Sandcastle等工具导出帮助文件文档时也会使用.因此,我强烈建议_not_使用`out Exception`模型(如果你想重新抛出,这通常会破坏堆栈跟踪.) (3认同)