【问题标题】:Is it acceptable/desire If I throw an error from callee rather than from caller是否可以接受/希望如果我从被调用者而不是调用者抛出错误
【发布时间】:2013-03-18 10:11:14
【问题描述】:

如果我从被调用者而不是调用者抛出错误,是否可以接受/希望?或者我应该从被调用者那里获取错误信息,然后从调用者那里抛出异常?哪一种是首选/渴望的方式?

public static List<ProductBuilder> GetProductBuilders(GetProductsRequest productsRequest)
{
    List<ProductBuilder> productBuilders = new List<ProductBuilder>();
    ...
    ... // Some logics to populate productBuilders

   if (productBuilders.Count == 0)
    {
        Logger.LogMessage(productsRequest.SessionId, "No ProductBuilders were created.");
        throw new ProductException(ProductException.ExceptionCode.SaveFailed, "No Service has qualified.");
    }

    return productBuilders;
}

【问题讨论】:

  • 空结果真的(总是)错误吗?
  • 同意@HenkHolterman,在我看来,空集合应该被视为不是例外情况。我想补充一点,如果可能,空集合总是比返回 null 更可取。要加深最后一个概念,请阅读this

标签: c# .net coding-style


【解决方案1】:

您的答案是坚持Single responsibility principle

在您提供的示例中,GetProductBuilders 方法具有(至少)两个职责:

  1. 填充对象集合
  2. 验证结果计数

如果您将代码重构为:

public static List<ProductBuilder> PopulateProductBuilders(...)
{
    // Logic to populate the collection
}

public static List<ProductBuilder> GetProductBuilders(GetProductsRequest productsRequest)
{
    var productBuilders = PopulateProductBuilders();
    if(!productBuilders.Any())
    {
        Logger.LogMessage(productsRequest.SessionId, "No ProductBuilders were created.");
        throw new ProductException(ProductException.ExceptionCode.SaveFailed, "No Service has qualified.");
    }
}

那么就很清楚哪个方法应该对空列表执行验证并抛出异常。

换句话说,如果您将方法的职责分开,您将更好地了解抛出异常的位置。

【讨论】:

  • SRP 仅适用于课程,对吗?不是吗?此外,如果我开始在方法级别应用 SRP,我的课程是否会以大量方法结束,而这些方法维护起来很乏味?您的意见请
  • @Al.Net,SRP 也应该应用于方法;一个方法应该只负责一个操作。如果您在一个类中有很多方法,那么您应该按功能对它们进行分组并将这些组移动到单独的类中。关于维护:维护一个简单的方法比维护一个过于复杂的方法容易得多;此外,更小的方法可以提高可读性和代码重用性。
【解决方案2】:

恕我直言,

如果您的任何类期望来自客户端的某些参数,您的框架类代码应该抛出异常,否则客户端应该处理返回的输出。

【讨论】:

    猜你喜欢
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多