2

I'm trying to calculate some Cyclomatic Complexity, hence trying to draw a Control Flow Graph. Firstly i'm trying to make it for a fairly simple method.

Firstly i tried drawing it for just the try part like this: Flow Graph

Heres the method:

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

How would i extend it to include the entire method, and the try part?

This is my first ever Control Flow Graph, so if i messed it up i would also like to know.

Anders Jensen
  • 330
  • 3
  • 20

2 Answers2

1

For my part i recommande you to use this code , more is simple , more is efficient

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

        return Ok();      
}
sayah imad
  • 1,507
  • 3
  • 16
  • 24
  • 1
    I agree in removing the try and catch, but i will keep the "affectedRows" variable. I know that your suggestion gives me the same result, with less code, but i like the readability in naming what i'm comparing. Thanks for your suggestion. – Anders Jensen May 21 '19 at 09:56
  • One problem: What if an exception gets thrown? OPs question indicates that `CreateCopy` can throw an exception – MindSwipe May 21 '19 at 10:33
1

I would create a TryCreateCopy method and do something very similar to @saya imad's answer
Something like this:

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

Where the TryCreateCopy method returns true when a copy was created without an exception being thrown, false if one has been thrown* and an out variable with the number of affected rows


* There is probably a better way of doing this than what I showed you (e.g validate method?) as try/ catch is quite resource intensive

MindSwipe
  • 7,193
  • 24
  • 47