Skip to content

The Gate Went Green and the File's Complexity Barely Moved

A complexity cap of 10 failed an 18-branch function, then passed after I split it into six. File cognitive complexity went 21 to 20. What to gate on.

· · 8 min read

Gates built on a cheap-to-move number tend to fail the same way, whether it's lines executed by tests or approvals on a pull request. I wanted to see how long a complexity gate survives contact with someone who just wants the check to go green. So I wrote the function, set the gate, and played that someone. It took one refactor.

What was the function, and what did the gate say?

A shipping quote calculator, 45 lines, the kind that collects one more case every quarter: weight bands, a destination zone, express and fragile surcharges, a coupon, optional insurance. It's a specimen I wrote for this post, and it isn't published here, so the exact scores below describe that one file. What isn't mine is the arithmetic that ESLint applied to it.

Environment: Node 22.23.3, ESLint 9.39.5, eslint-plugin-sonarjs 4.2.2, macOS on arm64. The gate was two rules: ESLint's built-in complexity at a maximum of 10, and sonarjs/cognitive-complexity at 15. (ESLint's own default for complexity is 20, per its docs. Ten is the figure McCabe proposed and NIST kept, with 15 tolerated in some cases, as the Wikipedia entry on cyclomatic complexity summarizes it.)

src/before.js
  2:8   error  Function 'quote' has a complexity of 18. Maximum allowed is 10
  2:17  error  Refactor this function to reduce its Cognitive Complexity from 21 to the 15 allowed

Red, correctly. The function has 17 decision points, so cyclomatic complexity is 18, and the cognitive score is 21 because several of the branches are nested. Nobody would argue.

How did I make it green?

I extracted methods until both rules stopped complaining. weightBand, zoneFactor, surcharges, applyCoupon, applyInsurance, and a short quote that calls them in order. No logic changed. A test run later in this post says so. Then I ran the gate again and it exited 0.

Here's the full picture, taken by setting both thresholds to 0 so ESLint reports every function's score:

Version Functions Max cyclomatic Sum cyclomatic Max cognitive Sum cognitive Gate
One function 1 18 18 21 21 Fails
Extracted into six 6 5 24 5 20 Passes

The worst function went from 21 to 5. The file's total cognitive complexity went from 21 to 20. Is that an improvement worth a green check? The code now reads in smaller pieces, and I'd call that a modest gain. The number that describes how much the code decides, though, hardly moved.

The cyclomatic sum went up, from 18 to 24, and the arithmetic is boring. Every function starts at 1, so five extra functions add five. The sixth point is real: a helper can't return early on behalf of its caller, so quote gained a factor === null check it never needed before. Splitting added a branch.

Did the behavior stay the same?

I'd rather not ask you to take my word for it, so I wrote a characterization test: 1,280 orders covering ten weights (including zero and negative), four zones (one invalid), express, fragile and insured on and off, and four coupon values. It compares the original function with the extracted one.

./src/after.js 1280 inputs compared, 0 differences

Twelve lines of test, and that's the whole guarantee that the refactor was a refactor. A complexity gate can't give you this. It reads the shape of the code and has no idea whether the shape changed meaning.

A per-function complexity cap measures where you put the braces, so the cheapest way to pass it is to move the code.

SHARE Post on X Bluesky

What would a harder-to-move number look like?

Look at the two columns that barely changed. Cognitive complexity went 21 to 20 as a file total while the per-function maximum fell by three quarters. SonarQube's documentation describes its overall complexity metric as basically the sum of the function-level scores, so a file-level total isn't a trick I invented. That sentence is about cyclomatic complexity, though. The page doesn't say how cognitive complexity rolls up, so summing the cognitive scores is my choice.

I'd gate on that. Concretely, per file, sum the cognitive scores, store the total on the main branch, and fail a change that raises it. The ratchet script is about 40 lines. Its core is a regex over ESLint's JSON output with the threshold forced to 0, which is fragile, because it parses a message string that the plugin is free to reword. I'd pin the plugin version.

const hit = msg.message.match(/Cognitive Complexity from (\d+)/);
if (hit) {
  sum += Number(hit[1]);
}
// fail when sum > baseline[file]

I ran it against the same file in three states.

State of quote.js Cognitive total Ratchet (baseline 21) Per-function gate
Original, one function 21 baseline fails
Extracted into six 20 ok passes
Extracted, plus one nested branch for US insurance 22 FAIL passes

Last row first. I added a nested if inside applyInsurance, a perfectly ordinary feature change, and the per-function gate stayed green because that function's score only rose to 4 against a cap of 15. The ratchet failed it at 22 against 21. Which of the two would you rather learn from?

Does a real simplification move the total?

Fair question, and I owed it an answer, because "the gate is gameable" is cheap if the honest version of the same work also doesn't register. So I rewrote the function a third way, with the branches turned into data: a list of weight bands, a table of zone factors, a one-line discount rule. Same 1,280 inputs, same 0 differences.

Version Functions Sum cyclomatic Sum cognitive
One function 1 18 21
Extracted into six 6 24 20
Table-driven 5 19 15

Cognitive total 15, down from 21. That's the number moving when the decisions actually moved, out of control flow and into data. I'm not claiming the table version is better code for every team; a reader who likes explicit if chains may disagree, and it's a reasonable disagreement. I'm saying the total can tell it apart from the extraction, and the per-function cap can't.

Where does this argument fail?

Three places, and I'd rather name them than have you find them.

First, I wrote all three versions. The extraction is the one I'd expect from a rushed edit, human or assistant, but it's still my guess about how people behave, not a measurement of anyone's pull requests. I haven't looked at how real teams get past a complexity gate.

Second, the total is gameable too. I checked one case: if (a && b && c && d) scores 2 cognitive and 5 cyclomatic, while if (a && b || c && d) scores 3 and 5. The plugin counts a run of the same operator once, so rewriting conditions to share an operator lowers the score, and the risk stays. No static number is immune; the aim is a number whose cheapest way to pass is also a way to improve the code, and I'd say a file total is closer to that than a per-function cap.

Third, complexity isn't a defect count. The Wikipedia entry notes that the correlation with defects is largely the correlation with size, and that reducing cyclomatic complexity hasn't been proven to reduce bugs. So a ratchet is a way to stop the number getting worse unnoticed, not evidence that you're getting safer. A failing ratchet should mean "explain this in the pull request", and sometimes the explanation is "the feature has more cases".

What would I change on Monday?

  • Keep the per-function cap if you like it, but treat it as a prompt to look, not as the gate.
  • Add a per-file total with a ratchet, and lower the baseline whenever a change brings the total down.
  • Before approving any refactor that exists to satisfy the gate, ask for the characterization test. If nobody wrote one, the green check certifies nothing.
  • Read the diff of the tests, not only the diff of the code. The grid above took twelve lines.

What does your complexity gate do when the same code gets moved into six functions? If you don't know, try it on a copy. It's an afternoon, and you'll learn what the gate was measuring.

Frequently Asked Questions

Can a cyclomatic complexity limit be passed without simplifying the code?
Yes. I split one 18-branch function into six helpers with no change in behavior across 1,280 test inputs. Every function then scored 5 or less and the limit of 10 passed, yet total cyclomatic complexity rose from 18 to 24 and total cognitive complexity only fell from 21 to 20.
What should a complexity gate measure instead of the worst function?
A per-file total, compared with a stored baseline so it can only stay level or go down. On my example the total moved from 21 to 20 when I only extracted methods, to 15 when I turned branches into data, and to 22 when I added one nested branch, which the ratchet caught and the per-function cap did not.
Is lower cyclomatic complexity proven to mean fewer bugs?
No. The Wikipedia entry on cyclomatic complexity notes that the correlation with defects is largely a correlation with program size, and that reducing the number is not proven to reduce errors. Treat a complexity ratchet as a way to stop drift, not as a safety measure.