How to indicate that a method was unsuccessful

前端 未结 16 1435
走了就别回头了
走了就别回头了 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条回答
  • 2020-12-31 08:31

    I would say best practice is a return value means success, and an exception means failure.

    I see no reason in the examples you provided that you shouldn't be using exceptions in the event of a failure.

    0 讨论(0)
  • 2020-12-31 08:32

    To summarise there are a couple of approaches you can take:

    1. When the return type is a value-type, like Point, use the Nullable feature of C# and return a Point? (aka Nullable), that way you can still return null on a failure
    2. Throw an exception when there's a failure. The whole argument/discussion regarding what is and isn't "exceptional" is a moot point, it's your API, you decide what's exceptional behaviour.
    3. Adopt a model similar to that implemented by Microsoft in the base types like Int32, provide a CalculatePoint and TryCalculatePoint (int32.Parse and int32.TryParse) and have one throw and one return a bool.
    4. Return a generic struct from your methods that has two properties, bool Success and GenericType Value.

    Dependent on the scenario I tend to use a combination of returning null or throwing an exception as they seem "cleanest" to me and fit best with the existing codebase at the company I work for. So my personal best practice would be approaches 1 and 2.

    0 讨论(0)
  • 2020-12-31 08:35

    Return Point.Empty. It's a .NET design patter to return a special field when you want to check if structure creation was successful. Avoid out parameters when you can.

    public static readonly Point Empty
    
    0 讨论(0)
  • 2020-12-31 08:39

    If the failure is for a specific reason then I think its ok to return null, or bool and have an out parameter. If however you return null regardless of the failure then I don't recommend it. Exceptions provide a rich set of information including the reason WHY something failed, if all you get back is a null then how do you know if its because the data is wrong, you've ran out of memory or some other weird behavior.

    Even in .net the TryParse has a Parse brother so that you can get the exception if you want to.

    If I provided a TrySomething method I would also provide a Something method that threw an exception in the event of failure. Then it's up to the caller.

    0 讨论(0)
提交回复
热议问题