Code Complexity: Levels, Metrics and Real-Repo Data

Raghav Chamadiya10 min read
On this page

Code complexity is how hard code is to understand, test and change. The standard metric is McCabe's cyclomatic complexity, which counts the independent paths through a function: one plus its decision points (if, loops, case, catch, &&, ||). McCabe's recommended limit is 10 per function.

Thomas McCabe published the metric in 1976, and it is still the number linters, IDEs and CI gates report first. We measured 200,744 production files across 160 popular public repos, so you can see what "above 10" looks like in practice.

Levels of code complexity

Code complexity is usually read in four levels by the worst function's cyclomatic score: 1 to 10 is simple, 11 to 20 is moderate, 21 to 50 is high, and above 50 is very high. McCabe himself proposed 10 as the upper limit for a function, and NIST Special Publication 500-235 keeps 10 as the starting point, allowing up to 15 only for teams with experienced staff and a strong test plan. The four bands are a common industry convention that many tools reuse. Tool defaults vary too: ESLint's complexity rule defaults to a maximum of 20.

Here is where 200,744 production files from 160 popular repos land, using each file's most complex function. Health is repowise's 1 to 10 file score, which takes complexity as one of its inputs, so the last columns show how the score treats each band, not independent proof of bugs.

LevelWorst function in the fileShare of filesFilesMedian file healthMedian non-comment linesReading
Simple1 to 1076.72%154,01510.0042Easy to hold in your head and to test.
Moderate11 to 2013.40%26,9068.04170Worth a look in review.
High21 to 507.79%15,6456.21274Hard to test fully; a refactoring candidate.
Very highAbove 502.08%4,1783.09595Often several jobs fused into one function.

Scroll the table sideways to see every column.

These are heuristics, not laws. A 12-case switch that maps codes to names scores 13 and reads fine, while a nested if ladder scores 5 and does not. That gap is why cyclomatic complexity is paired with a reading-cost metric, covered below.

What makes code complex?

Code gets complex when one function holds many decisions, deep nesting, or several jobs at once. Branches multiply the paths a reader and a test suite must cover, nesting forces the reader to keep every outer condition in mind, and mixed responsibilities mean a change for one reason touches lines written for another.

Here is a complex version of a small pricing rule, scoring 6:

python
def discount(user, cart):
    if user is not None:
        if user.active:
            if cart.total > 100:
                if user.tier == "gold" or user.tier == "silver":
                    return 0.2
                else:
                    return 0.1
            else:
                return 0.0
        else:
            return 0.0
    return 0.0

And a flat rewrite with a guard clause and a lookup, scoring 4, same behavior:

python
RATES = {"gold": 0.2, "silver": 0.2}

def discount(user, cart):
    if user is None or not user.active or cart.total <= 100:
        return 0.0
    return RATES.get(user.tier, 0.1)

The rewrite has a nesting depth of 1 instead of 4. Most complex code in real repos is this shape at a larger scale: simple logic that accumulated branches over time.

Types of code complexity

Code complexity comes in several kinds, and each metric measures a different one.

  • Cyclomatic complexity counts independent paths, so it tells you how many tests a function needs. The next section shows the math, and the glossary entry on cyclomatic complexity has the short definition.
  • Cognitive complexity charges more for each level of nesting, so it tells you how hard a function is to read. See the cognitive complexity definition and the comparison with cyclomatic complexity.
  • Essential and accidental complexity is Fred Brooks's split from "No Silver Bullet" (1986). Essential complexity comes from the problem itself; accidental complexity comes from how we chose to build the solution. Tools can only shrink the second kind.
  • Big-O complexity is a different thing. It describes how running time or memory grows with input size, not how hard code is to read or test. A function can be O(n) and tangled, or O(n squared) and trivial to follow.

How McCabe complexity is calculated

McCabe complexity is M = E - N + 2P, where E is the edges and N the nodes of the function's control-flow graph and P the number of connected components. For a single function P is 1, and the formula reduces to the count that tools actually use: decision points plus one.

A plain if/else has four nodes (the condition, the two branches and the join) and four edges, so M = 4 - 4 + 2 = 2. One decision, two paths.

Here is a worked example in Python:

python
def shipping_cost(order, express):
    if order.total > 100:                 # +1
        return 0
    cost = 5
    for item in order.items:              # +1
        if item.heavy and express:        # +1 for if, +1 for and
            cost += 8
        elif item.region == "intl":       # +1
            cost += 12
    return cost

There are five decision points, so the cyclomatic complexity is 5 + 1 = 6. That also means six independent paths, and six test cases are enough to exercise every branch at least once.

Counting rules differ a little by tool. radon for Python adds one for if, elif, for, while, except, with, assert, comprehensions and each and or or, and nothing for else or finally. gocyclo for Go starts at 1 and adds one per if, for, case, && and ||. ESLint's complexity rule also counts ternaries, optional chaining, default parameters and logical assignment, and offers a modified variant that counts a whole switch as one. The same function can score a point or two differently across tools, so compare numbers from one tool over time.

How complex is real code? Our data from 160 repos

In 160 public GitHub repos with 1,000+ stars (production code only, measured November 2026), 23.3% of files contain a function above McCabe's limit of 10, 9.9% above 20, and 2.1% above 50. The dataset is 200,744 production files. Test, generated and vendored code is excluded.

One definition matters for every number below. We measure the worst function in each file (its highest McCabe complexity), not every function, so a "file above 10" is a file that contains at least one function above 10.

Statistic, worst function per fileValue
Median (p50)4
p9020
p9973
Maximum3,933
Files above 1023.3%
Files above 209.9%
Files above 502.1% (4,178 files in 133 repos)
Max nesting depth p50 / p90 / p991 / 4 / 6

Scroll the table sideways to see every column.

Half of all files have a worst function of 4 or less. The pain sits in the tail: the p99 file has a function of 73. Counting each repo once, the median repo has 20.3% of its files above 10, 6.8% above 20 and 0.8% above 50. 158 of the 160 repos have at least one file with a function above 10, and 133 have a file above 50.

Complexity by language

JavaScript repos run hottest: 44.0% of files contain a function above 10, against 17.4% in Go. The table covers the languages with 10 or more repos in the dataset, pooled across files, and each percentage is the share of files whose worst function exceeds the threshold.

Primary languageReposFilesp50p90p99Above 10Above 20Above 50
Python4439,4754196722.2%8.46%1.7%
TypeScript4376,2505238228.6%12.16%2.6%
Go2115,2972154417.4%5.75%0.7%
JavaScript1316,63383915444.0%24.31%6.1%
Rust1010,9663196920.5%8.46%1.7%

Scroll the table sideways to see every column.

Complexity is concentrated in a few files

In the median repo, the top 10% of files hold 87% of the excess above McCabe's limit of 10 (counting each file's worst function), and the top 1% hold 26%. Measured across all files' worst-function scores (across all files, not only those above 10), the top 1% hold 9.5% and the top 10% hold 42.6%.

Complexity is one of several code quality metrics, and the others, such as churn and coupling, tell you which of these files are worth the time. So a repo is not uniformly tangled. A short list of files carries most of the excess, which is why ranking beats blanket rules: fix the top files first and most of the excess goes with them.

Big files carry the complexity

Of files over 1,000 non-comment lines, 61.4% contain a function above 20; of files of 200 or fewer, 3.6% do. Median file size grows with the worst function, too.

The levels table above shows file health and size by band: the median very-high file is 595 non-comment lines, against 42 for a simple one.

Other code complexity metrics

Cyclomatic complexity is one of several measures, and each answers a different question.

  • Cognitive complexity scores how hard a function is to read by charging more for each level of nesting. SonarSource defined it in a white paper by G. Ann Campbell. It rates a flat switch low and a deep if ladder high, the reverse of cyclomatic. See the cognitive complexity definition and the side-by-side comparison with cyclomatic complexity.
  • Nesting depth is the deepest level of indented control flow in a function. In our data the median file's deepest nesting is 1, p90 is 4 and p99 is 6. Three levels deserves a look; four usually needs flattening.
  • Halstead metrics (Maurice Halstead, 1977) count operators and operands to derive volume, difficulty and effort. Volume is the one that survives in practice, mainly as an input to the maintainability index.
  • Maintainability index folds Halstead volume, cyclomatic complexity and lines of code into one 0 to 100 number. Visual Studio rates 20 to 100 as good, 10 to 19 as moderate and 0 to 9 as low. radon's docs call its own variant "still a very experimental metric", so treat the index as a rough sort key.
  • Function length (lines of code per function) is not a complexity measure in the strict sense, but it correlates with the metrics above and is the cheapest to compute.

If you track only one number, track cyclomatic complexity per function. If you track two, add nesting depth.

How to measure code complexity in practice

Pick the standard tool for your language and set the threshold in CI. All of these report per-function complexity.

LanguageToolCommandNotes
Pythonradonradon cc -s -a src/Also radon mi for the maintainability index.
JavaScript, TypeScriptESLint complexity"complexity": ["error", { "max": 10 }]Default max is 20. variant: "modified" counts a switch once.
Gogocyclogocyclo -over 10 .Install with go install github.com/fzipp/gocyclo/cmd/gocyclo@latest. Exits 1 when anything is over.
RustClippy cognitive_complexitycognitive-complexity-threshold = 25 in clippy.tomlLint sits in the restriction group, allowed by default.
C# and other .NETVisual Studio code metricsAnalyze, Calculate Code MetricsAlso reports maintainability index and class coupling.
Many languageslizardlizard -C 10 src/Supports 30+ languages including Java, C and C++, Kotlin, Swift and PHP. Exits non-zero on warnings.

Scroll the table sideways to see every column.

Run one tool per language and gate on a threshold you can meet, not on McCabe's 10 from day one. A repo with 20% of its files above 10 will fail every build, so start at the current p90 and lower the bar as the list shrinks, or gate only on files a pull request touches.

How repowise surfaces code complexity

repowise reports high cyclomatic complexity and deep nesting as findings on every file and ranks them with git history, so you start with the complex code that changes. Each file gets a 1 to 10 code health score from deterministic detectors; the size family covers long or high-CCN functions and the structural family covers deep nesting, god classes and complex conditions (code health docs). No LLM key is needed for the scores.

The fix-first list pairs a complex function with how often its file changed:

text
 1. Extract the retry branch from parse_config now · effort M · +1.4 health on this file
    src/config/loader.py:212
    CCN 47 and nesting 6 in a file changed 19 times this quarter.

A function that scores 47 in a file nobody touches matters less than one that scores 20 in a file changed weekly, and the ranking puts them in that order. Agents can pull the same data through the get_health MCP tool.

How to reduce code complexity

Reduce complexity by removing branches from the function, not by moving them somewhere you stop counting. Four moves cover most cases:

  1. Guard clauses. Return early on a failed precondition so the main path stays flat.
  2. Extract by phase. A function that parses, validates and executes becomes three functions, each under 10.
  3. Replace ladders with data. A lookup table beats a long if/elif chain.
  4. Split the file. Big files carry the complexity (61% of files over 1,000 non-comment lines hold a function above 20), so splitting a god file removes the places it can hide.

Behavior must stay the same, so lean on tests before you start. The refactoring guide covers the safe order, spaghetti code covers the dependency side of the same problem, and what is technical debt covers where complexity sits in the larger picture. The standards behind these limits are in coding standards and clean code, the full picture is in the code quality guide, and static analysis tools for large codebases compares the tools that enforce them.

FAQ

What is code complexity?
Code complexity is a measure of how hard code is to understand, test and maintain. It is usually quantified with cyclomatic complexity (execution paths), cognitive complexity (reading effort) and nesting depth. Algorithmic complexity (big O) is a separate idea about how running time and memory grow with input size.
What are the levels of code complexity?
By the worst function's cyclomatic score, the usual levels are simple (1 to 10), moderate (11 to 20), high (21 to 50) and very high (above 50). In 160 popular repos, 76.72% of files are simple, 13.40% moderate, 7.79% high and 2.08% very high.
What is complex code?
Complex code has many decision points, deep nesting or several responsibilities in one function, so it takes more effort to read, test and change safely. A function with a cyclomatic score above 10 is the usual flag.
How do you measure code complexity?
Run a per-function tool for your language, such as radon for Python, ESLint's complexity rule for JavaScript and TypeScript or gocyclo for Go, and gate CI on a threshold your repo can meet. Start at your current p90 and lower it over time.
What is McCabe complexity?
McCabe complexity is another name for cyclomatic complexity, the metric Thomas McCabe defined in 1976. It counts the linearly independent paths through a function, computed as M = E - N + 2P on the control-flow graph, or decision points plus one.
What is a good cyclomatic complexity?
Keep functions at 10 or below, which is McCabe's recommended limit. Scores of 11 to 20 are moderate, 21 to 50 are high, and above 50 is a strong sign the function should be split. In 160 popular repos, half of all files have a worst function of 4 or less.
How do you calculate cyclomatic complexity?
Count the decision points in the function (if, elif, loops, case, catch, &&, ||, ternaries) and add one. On a control-flow graph the same number is edges minus nodes plus two. A function with five decision points has a complexity of 6.
What is the difference between cyclomatic and cognitive complexity?
Cyclomatic complexity counts paths, so it tells you how many tests a function needs. Cognitive complexity adds a penalty per nesting level, so it tells you how hard the function is to read. A flat switch scores high on the first and low on the second.
What does cyclomatic mean?
Cyclomatic refers to the cyclomatic number from graph theory: the number of independent cycles in a graph. McCabe applied it to a program's control-flow graph, where each independent cycle corresponds to one more path through the code.
What cyclomatic complexity is too high?
Above 10 is McCabe's threshold, above 20 is the common "high" band, and above 50 is rare and usually a candidate for splitting. In our data, 23.3% of files have a function above 10, 9.9% above 20 and 2.1% above 50.
Which tool measures cyclomatic complexity?
radon for Python, the ESLint complexity rule for JavaScript and TypeScript, gocyclo for Go, Visual Studio code metrics for C#, and lizard for more than 30 languages. repowise reports it per function and per file across languages and ranks the results against git history.