How to indicate that a method was unsuccessful

前端 未结 16 1551
走了就别回头了
走了就别回头了 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:15

    The bool TrySomething() is at least a practice, which works ok for .net's parse methods, but I don't think I like it in general.

    Throwing an exception is often a good thing, though it should not be used for situations you would expect to happen in many normal situations, and it has an associated performance cost.

    Returning null when possible is in most cases ok, when you don't want an exception.

    However - your approach is a bit procedural - what about creating something like a PointCalculator class - taking the required data as parameters in the constructor? Then you call CalculatePoint on it, and access the result through properties (separate properties for Point and for Success).

提交回复
热议问题