【问题标题】:How do i express Try/Catch in a control flow graph?如何在控制流图中表达 Try/Catch?
【发布时间】:2019-10-07 15:32:57
【问题描述】:

我正在尝试计算一些圈复杂度,因此尝试绘制控制流图。首先,我试图将其做成一个相当简单的方法。

首先,我尝试仅将其绘制为 try 部分,如下所示:

方法如下:

    [HttpPost]
    public ActionResult GraphMethod([FromForm]string str)
    {
        try
        {
            int affectedRows = this._copyManager.CreateCopy(str);
            if (affectedRows < 1) return BadRequest("Error!");

            return Ok();
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

我将如何扩展它以包含整个方法和 try 部分?

这是我的第一个控制流图,所以如果我搞砸了,我也想知道。

【问题讨论】:

  • 不应使用异常来控制流(如here 所述),因此(至少在我的逻辑中)不会在控制流图中表示
  • catch (Exception ex) 是一个非常糟糕的反模式。
  • @MindSwipe 谢谢,我将删除我的 try/catch。

标签: c# cyclomatic-complexity control-flow-graph


【解决方案1】:

就我而言,我建议您使用此代码,越简单,越高效

[HttpPost]
public ActionResult GraphMethod([FromForm]string str)
{       
        if (this._copyManager.CreateCopy(str) < 1) 
            return BadRequest("Error!");

        return Ok();      
}

【讨论】:

  • 我同意删除 try and catch,但我会保留“affectedRows”变量。我知道您的建议给了我相同的结果,但代码更少,但我喜欢命名我正在比较的内容的可读性。感谢您的建议。
  • 一个问题:如果抛出异常怎么办? OPs 问题表明CreateCopy 可以抛出异常
【解决方案2】:

我会创建一个TryCreateCopy 方法并做一些与@saya imad 的回答非常相似的事情
像这样的:

[HttpPost]
public ActionResult GraphMethod([FromForm]string str)
{ 
    // These two if statements can be concatenated into one, 
    // but that would be a bit hard to read
    if (this._copyManager.TryCreateCopy(str, out var affectedRows))
        if (affectedRows > 1)
            return Ok();

    return BadRequest("Error!");
}

// _copyManager Method, there's probably a better way for you
public bool TryCreateCopy(string str, out int affectedRows)
{
    try
    {
        affectedRows = CreateCopy(str);
    }
    // Please also don't do `catch (Exception)`, 
    // if you know which exception gets thrown always catch that
    catch (Exception e)
    {
        affectedRows = -1;
        return false;
    }

    return true;
}

当创建副本且未抛出异常时,TryCreateCopy 方法返回 true,如果已抛出异常,则返回 false* 和带有受影响行数的 out 变量


* 可能有比我向您展示的更好的方法(例如 validate 方法?)因为 try/catch 非常耗费资源

【讨论】:

    猜你喜欢
    • 2015-02-21
    • 1970-01-01
    • 2019-11-15
    • 2012-02-02
    • 1970-01-01
    • 2010-11-23
    • 2012-11-25
    • 2021-02-13
    • 2021-12-03
    相关资源
    最近更新 更多