How to indicate that a method was unsuccessful

前端 未结 16 1550
走了就别回头了
走了就别回头了 2020-12-31 08:03

I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For

16条回答
  •  猫巷女王i
    2020-12-31 08:16

    A pattern that I'm experimenting with is returning a Maybe. It has the semantics of the TryParse pattern, but a similar signature to the null-return-on-error pattern.

    I'm not yet convinced one way or the other, but I offer it for your collective consideration. It does have the benefit of not requiring a variable to defined before the method call to hold the out parameter at the call site of the method. It could also be extended with an Errors or Messages collection to indicate the reason for the failure.

    The Maybe class looks something like this:

    /// 
    /// Represents the return value from an operation that might fail
    /// 
    /// 
    public struct Maybe
    {
        T _value;
        bool _hasValue;
    
    
        public Maybe(T value)
        {
            _value = value;
            _hasValue = true;
        }
    
        public Maybe()
        {
            _hasValue = false;
            _value = default(T);
        }
    
    
        public bool Success
        {
            get { return _hasValue; }
        }
    
    
        public T Value
        {
            get 
                { // could throw an exception if _hasValue is false
                  return _value; 
                }
        }
    }
    

提交回复
热议问题