避免代码复制

本文关键字:复制 代码 | 更新日期: 2024-09-23 02:37:31

在我的代码中,我有很多函数都有这个签名(params+return类型),它们都使用相同的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);
    }
}

有没有一种模块化的方式可以在我的代码中进行行为,而不需要复制?有没有我可以使用的设计或建筑模式?如果是,是哪一个?

避免代码复制

您可以像这样进行因子分解:

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;
       };
}