0

I am trying to understand Cyclomatic complexity - mainly to get my head around if it's useful.

I did a quick check of my codebase and all the functions had a complexity < 6. This led me to try and write a "highly" complex function, but it seems very hard to do. I tried:

def foo(x):
    
    with _ as file:
        for _ in range(500):
            try:
                while x: 
                    if True:
                        pass
                    elif False:
                        pass
                    else:
                        pass
            except:
                pass
            else:
                pass
                
        return True

and this got a score of 6.

I've read guidance that anything with a Cyclomatic complexity under 20 is "fine", but I can't imagine functions (at least in Python) with 10+ complexity.

What causes high Cyclomatic complexity in practice? Or am I missing something?

MYK
  • 1,988
  • 7
  • 30
  • Lots of things, but basically gigantic functions full of business logic, lots of flags/conditions, etc. By reasonably breaking your code into reasonably sized functions with specific semantic purposes you can avoid that kind of thing. The fact that you have not seen such code in "the wild", you should consider yourself lucky :) – Cory Kramer Jan 06 '22 at 17:50
  • You're generally gonna see high cyclomatic complexity in _very long_ functions with a lot of branching and/or looping behavior, three to four indentations deep. These are generally functions that accomplish single, but very large, tasks that have multiple steps. It's usually possible to put each step in its own method, which would lower cyclomatic complexity at the cost of increasing the number of methods you need to keep track of and document, and tightly coupling those methods together in ways that might not be desirable or maintainable. – Green Cloak Guy Jan 06 '22 at 17:54
  • Interesting @CharlesDuffy, but not sure we are talking about the same thing. You seem to be talking about time complexity, I'm focusing on Cyclomatic complexity (a measure of independent paths through a program's source code). – MYK Jan 06 '22 at 21:44
  • I'm with Cory here -- if you haven't seen cases where that's nasty, you're fortunate enough to have not dealt with legacy codebases that have grown by accretion. You'll run into them eventually. – Charles Duffy Jan 06 '22 at 21:48
  • Does this answer your question? [What is Cyclomatic Complexity?](https://stackoverflow.com/questions/911637/what-is-cyclomatic-complexity) – wovano Jan 06 '22 at 22:06
  • No, but thank you. The closest one I could find was [avoid-high-cyclomatic-complexity](https://betterembsw.blogspot.com/2014/06/avoid-high-cyclomatic-complexity.html) because it had an illustration of what a "complex" function might look like. – MYK Jan 06 '22 at 22:19

0 Answers0