【问题标题】:Avoid code replication避免代码复制
【发布时间】:2015-05-03 23:15:39
【问题描述】:

在我的代码中,我有许多具有此签名的函数(参数 + 返回类型),它们都使用相同的 try-catch 子句。

public ActionResult methodName(int id)
{
    try
    {
        //Some specific code here
        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }
    catch (Exception ex)
    {
        return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
    }
}

现在,这被一遍又一遍地复制,我知道复制是不好的。 发生这种情况的原因是因为我希望代码能够返回多个HttpStatusCodeResult,但我不知道更好的方法。

在本例中,我返回一个内部服务器错误和一个 OK 答案。但是如果我想返回另一种类型的错误呢?

public ActionResult methodName(int id)
{
    try
    {
        //Some specific code here
        if(conditionA)
            return return new HttpStatusCodeResult(HttpStatusCode.NotFound, "No Hamsters found!")
        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }
    catch (Exception ex)
    {
        return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
    }
}

在我的代码中是否有一种无需复制的模块化方式来实现行为?有我可以使用的设计或架构模式吗?如果有,是哪一个?

【问题讨论】:

  • 使用异常过滤器代替try..catch
  • 你能举个例子吗?我不知道你在说什么:S
  • 复制与创建异常有关,而不是处理它们。过滤器不会做:S
  • 您可以删除try..catch 块并使用过滤器来过滤return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);,以防出现异常。然后你就剩下if (condA) { return new (...) } else { return new (...) }。如果您甚至不想这样,您可以在变量中设置状态代码和文本,然后 return new HttpStatusCodeResult(statusCode, statusText) ... 在每个操作方法中重复此操作。

标签: c# design-patterns exception-handling architectural-patterns


【解决方案1】:

你可以这样分解:

public static class Helper
{
    public static ActionResult TryCatch(Func<ActionResult> funk)
    {
        try
        {
            if (funk != null)
            {
                ActionResult result = funk();
                if (result != null)
                    return result;
            }
        }
        catch (Exception ex)
        {
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
        }
        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }
}

然后这样称呼它:

public ActionResult methodName(int id)
{
    return Helper.TryCatch(() => 
       {
            //Some specific code here
            if(conditionA)
                return return new HttpStatusCodeResult(HttpStatusCode.NotFound, "No Hamsters found!")
            return null;
       };
}        

【讨论】:

  • 我真的需要在最后返回 null 吗?除此之外,它对我来说似乎是一个很酷的解决方案。这是使用模式还是什么?
  • 它是一个 Func,所以你必须返回一些东西(Func 就像一个返回 T 的方法,所以如果你不返回一些东西,你就会有编译错误)。这不是一种设计模式,或者如果它是某种东西,它是 DRY 原则的实现 :) en.wikipedia.org/wiki/Don%27t_repeat_yourself
猜你喜欢
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多